Argoron Argoron - 24 days ago 7
jQuery Question

Uniform formatting of a selection of cells in various tables with jQuery

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:

Answer Source

You're selecting only the first td element that is the descendent of a tr.reg:even row.

Try using the :nth-child() alternative:

$('table tr:odd td:nth-child(2)').css('background-color','#ffa');​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

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:

...but it presents me with a problem. I've edited your jsfiddle demo to add a row in the first table thus giving it an uneven number of rows. Now the second table's rows are reversely highlighted which is not what I was looking for. Do you have a fix for this ?

Yeah, I...missed the obvious (somehow). I've amended the above code to look at each table in turn and then look for the :odd rows and the nth-child():

$('table').find('tr:odd td:nth-child(2)').css('background-color','#ffa');​

JS Fiddle demo.