Set css style on first row of the table on case first row has rowspan - multi table

Viewed 185

There are many tables, I want to set css style on first row of the table on case where first row has rowspan. According this question, I find a way to set style. but there is a bug on case multi table.

Need to set style on first row and rowspan of it, just like this image: enter image description here

Here is the script code:

document.querySelectorAll("table").forEach(table => {
  let tr = table.getElementsByTagName("tr")[0];
  let td = tr.getElementsByTagName("td")[0];
  let rowspan = td.rowSpan ? td.rowSpan : 1;
  var nodes = document.querySelectorAll(`tbody tr:nth-child(-n+${rowspan})`);
  for (let i = 0; i < nodes.length; i++) {
    nodes[i].style.background = "#1DA6C0";
  }
});

Sample: https://jsfiddle.net/sarzin/mrda7s6x/5/

2 Answers
  1. Detect the needed rowspan for particular table. Extend the selector string for querySelectorAll function as needed.

  2. Run querySelectorAll function on that particular table, not for whole document

Applying above two points, your js code should be something like this:

document.querySelectorAll("table").forEach(table => {
    let tr = table.getElementsByTagName("tr")[0];
  let tds = tr.getElementsByTagName("td");
  let selectorStr ="tbody tr:nth-child(1)"

  let maxRowspan = 1;

  for (let i = 0; i < tds.length; i++) {
    if(maxRowspan < tds[i].rowSpan)
    {
        maxRowspan = tds[i].rowSpan
      selectorStr += " , tbody tr:nth-child(" + maxRowspan + ")"
    }
  }

  var nodes = table.querySelectorAll(selectorStr)

  for (let i = 0; i < nodes.length; i++) {
    nodes[i].style.background = "#1DA600";
  }
});

Here is my edit on your fiddle.

I actually would use th instead of td for the first row. First, if it's a header th is a better choice anyway and second you don't need any js for solving this.

th {
  background-color: #1DA6C0;
  text-align: left;
  font-weight: normal;
}
<table>
  <tbody>
    <tr>
      <th width="64">8"</th>
      <th width="64">6"</th>
      <th width="64">5"</th>
      <th width="64">4"</th>
      <th width="64">3"</th>
      <th width="74">2"</th>
      <th width="100">inch</th>
    </tr>
    <tr>
      <td rowspan="2">76</td>
      <td rowspan="2">69</td>
      <td rowspan="2">48</td>
      <td rowspan="2">27</td>
      <td rowspan="2">20</td>
      <td rowspan="2">11</td>
      <td rowspan="2" width="100">A</td>
    </tr>
  </tbody>
</table>
<br>
<table>
  <tbody>
    <tr>
      <th rowspan="2" width="110">Status</th>
      <th width="110">time</th>
      <th width="110">power</th>
      <th rowspan="2" width="110">second status</th>
      <th width="110">D</th>
    </tr>
    <tr>
      <th>Time</th>
      <th>( bar )</th>
      <th>D1 </th>
    </tr>
    <tr>
      <td>A</td>
      <td>1</td>
      <td>32</td>
      <td>(B)</td>
      <td>25</td>
    </tr>
  </tbody>
</table>

Related