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

Asked

Viewed 1,474 times

3

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 that tr was > 0. This is possible 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 <--
}
});

2 answers

2


See the example using the function find()

Tip: Instead of using the innerHTML javascript, please use the html() jQuery, you may experience problems in some browsers using the innerHTML already the html() will instantiate the function of Javascript 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>

  • 1

    Very interesting your tip, I didn’t know it... Thanks for the help, it was similar to what I had already done, but simpler and efficient.

0

After creating the question I did a quick search and managed to solve the problem using the jquery’s Closest() method, thus:

$('.tr-child td:nth-child(4)').each(function(index, element){
  if(element.innerHTML > 0){
    $(element).closest('tr').attr('id','colorir');
  }
});
#colorir td{
  color:green;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.