javascript – How to change the color of a tr according to the data of a td?

Question:

I have some tr in the table that contains the tr-child class and I would like to change their color when the value of the fourth column of this tr is > 0. Is this possible to do with jquery ?

had already done something…

$('.tr-child td:nth-child(4)').each(function(index, element){
if(element.innerHTML > 0){
// precisaria setar a tr referente a esta td aqui <--
}
});

Answer:

See the example using the find() function

Tip: Instead of using JavaScript's innerHTML , use jQuery's html() , you may have problems in some browsers using innerHTML as html() will instantiate the JavaScript function after some checks.

$('table tr').each(function() {
  var valor = parseInt($(this).find('td:nth-child(3)').html());
  if (valor > 60)
    $(this).addClass('colorido');
});
.colorido {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>
Scroll to Top