I have a page which contains several tables, and I would like to format each table so that the second cell of each other row has a specific background color.
I have tried the following jQuery code as suggested in an answer to the initial version of this question :
$('table tr:odd td:nth-child(2)').css("background-color", "#F6F3EE");
This works fine as long as all tables have an even number of rows. If that is not the case, the formatting is inverted, as if jQuery considered the s as being part of one single table and doesn’t reinitiate the counter at each table.
Here’s a link to a js fiddle to illustrate the problem:
You’re selecting only the first
tdelement that is the descendent of atr.reg:evenrow.Try using the
:nth-child()alternative:JS Fiddle demo.
Note: you have to remember that the CSS
:nth-child()is one-based, not zero-based (as JavaScript is).Edited in response to OP’s comment, below:
Yeah, I…missed the obvious (somehow). I’ve amended the above code to look at each
tablein turn and then look for the:oddrows and thenth-child():JS Fiddle demo.
References:
find().:nth-child().:oddselector.