Reputation: 3081
I wish to loop through the table and color the TD of every value that is negative. Right now it colors the whole row, what can I change to fix it?
$('.my-table tr').each(function(index, tr) {
var lines = $('td', tr).map(function(index, td) {
return $(td).text();
});
if( lines[1] < 0 ) {
$(this).css('background-color', 'red');
}
});
Upvotes: 1
Views: 2030
Reputation: 5993
$('.my-table tr').each(function(index, tr) {
var lines = $('td', tr).map(function(index, td) {
if ( $(td).text() < 0 ) $(td).css('background-color', 'red') #de Fixed.
return $(td).text();
});
})
Optimized version:
$('.my-table tr td').each(function(index, td) {
if ( $(td).text() < 0 ) {
$(td).css('background-color', 'red')
}
})
Upvotes: 1
Reputation: 95252
You're applying the css to the <tr>
. You want to apply it only to the <td>
that has the negative value.
Upvotes: 0
Reputation: 150253
Dude, it's jQuery, write less do more:
$('.my-table td').filter(function() {
return parseFloat($.trim(this.innerHTML)) < 0;
}).css('background-color', 'red');
Upvotes: 2