Reputation: 1374
Been Googling this for over an hour, and getting answers to much more complex questions but not this simple one, and my Dummies book is no help.
I want to change the background of a row if a particular cell has a value. So:
$('#MyTable tr').each (function(index) {
$(this).css('background-color', '#FCDCE4');
});
Works fine to change the bg color in every row, but how can I do this only in rows where column 30 has a value? I could probably give my target cell a css class and do it that way, but I'd really rather learn to use jQuery properly (so that I don't need to keep posting elementary questions).
Upvotes: 3
Views: 2033
Reputation: 185893
First, put the reference to the table inside a variable:
var table = $( '#myTable' )[0];
You probably want to keep this reference available throughout your application (so that all your methods have access to it).
Next:
var nr = 30; // the column number
$( table.rows ).each( function () {
if ( $( this.cells ).eq( nr - 1 ).text() ) {
$( this ).addClass( 'selected' );
}
});
So, if the 30. cell has any text-content, add the 'selected'
class to the row.
Live demo: http://jsfiddle.net/2C6C7/
Upvotes: 1
Reputation: 101604
$('table td:nth-child(30):empty').each(function(){
$(this).css('background-color','#FCDCE4'); // empty column
});
nth-child
selector to grab the 30th column
:empty
to grab empty cells.
Example on jsFiddle can be found here: http://jsfiddle.net/pYA4U/
Upvotes: 3
Reputation: 60448
You can use jQuery .children()
and .eq()
to get the cell 30.
Note that .eq() is zero based, so you need to use 29 to get the 30th cell
$('#MyTable tr)').each (function(index) {
var cell = $(this).children("td").eq(29)
// your if condition
$(this).css('background-color', '#FCDCE4');
});
Upvotes: 5