Home > Enterprise >  How can you use css to style all <td> elements in a table when one of the <td> elements
How can you use css to style all <td> elements in a table when one of the <td> elements

Time:03-22

I need to highlight an entire row of in a table when one of the elements contains a certain class. Example:

.whole-row-red-background {
  background-color: red;
}
<table>
  <tbody>
    <tr>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td class='whole-row-red-background'></td>
      <td></td>
      <td></td>
    </tr>
  </tbody </table>

In the example above, only the first cell (the first td) of the second row in the table is set with a red background. Under this scenario (first <td> in the row has this class) I need all <td> elements in the row to have a red background.

CodePudding user response:

You could use the general sibling selector. More info here: https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator

Here is your updated snippet:

.whole-row-red-background {
  background-color: red;
}

.whole-row-red-background ~ td {
  background-color: red;
}
<table>
  <tbody>
    <tr>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td class='whole-row-red-background'></td>
      <td></td>
      <td></td>
    </tr>
  </tbody </table>

CodePudding user response:

let td = document.getElementsByClassName("whole-row-red-background")[0]
let tr = td.closest("tr")
tr.style.backgroundColor='red'
.whole-row-red-background {
  background-color: red;
}
<table>
  <tbody>
    <tr>
      <td>x</td>
      <td>y</td>
      <td>z</td>
    </tr>
    <tr>
      <td class='whole-row-red-background'>a</td>
      <td>b</td>
      <td>c</td>
    </tr>
  </tbody> </table>

  • Related