Edward
Edward

Reputation: 3081

Jquery Looping through a table to find specific TD

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?

http://jsfiddle.net/LEnRj/

Jquery

$('.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

Answers (3)

digitalextremist
digitalextremist

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

Mark Reed
Mark Reed

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

gdoron
gdoron

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');

Fixed Fiddle

Upvotes: 2

Related Questions