'How do I conditionally change the colour of my table row in HTML?

I have a table where the background colour of one of the rows needs to be changed dynamically. For example, if the data is greater than 5, the colour should be green, else it should be red.



Solution 1:[1]

can be done with css (if the structure fits)

td {
  border: 1px solid ;
  padding: 5px;
  position: relative;
  width: 50px;
}

.item {
  position: relative;
  z-index: 2;
}

.bg {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.item:nth-child(1) ~ .bg {
  background: blue;
}
.item:nth-child(2) ~ .bg {
  background: darkblue;
}
.item:nth-child(3) ~ .bg {
  background: red;
}
.item:nth-child(4) ~ .bg {
  background: darkgreen;
}
.item:nth-child(5) ~ .bg {
  background: darkorange;
}
<table>
  <tr>
    <td>
      <div class="item">1</div>
      <div class="bg"></div>
    </td>
    <td>
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="bg"></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="bg"></div>
    </td>
    <td>
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="bg"></div>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <span class="item">1</span>
      <span class="item">2</span>
      <strong class="item">3</strong>
      <i class="item">4</i>
      <div class="item">5</div>
      <div class="bg"></div>
    </td>
  </tr>
</table>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Юрий Копоть