views:

516

answers:

2

Let's say I have two tables that look like this:

TH   TH   TH   TH  
TD   TD   TD   TD  
TD   TD   TD   TD  

and

TH   TH   TH   TH  
TH   TD   TD   TD  
TH   TD   TD   TD  

I'd like to select the 3rd column in each.

At first I was using nth-child as such:

$('table tr td:nth-child(3)')

But that's not going to work, as 3rd TD is in a different column in each table.

What I need in pseudo code is 'get the 3rd TD or TH in each row'.

I assume I need to use $.siblings but not entirely sure.

+2  A: 

You need to write $('table tr *:nth-child(3)')

The :nth-child selector selects elements that are the nth child of their parent, regardless of how many siblings are matched by the selector.

You're (incorrectly) describing the :eq selector.

SLaks
Actually, he's describing something that doesn't exist as a selector at all. `table tr td:eq(3)` would return the fourth (0 based index for eq) td in the table inside of a tr, and no others.
gnarf
tr:nth-child(3) returns the 3rd TR. I need to return the 3rd child of the TR. But that child may be a TD or TH
DA
@DA: Then you need to write `tr *:nth-child(3)`.
SLaks
Thanks, SLaks! The space/asterisk) was the key.
DA
+3  A: 

This works for me:

$('table tr :nth-child(3)').css('background-color', 'red');

It sets the background color of the 3rd column to 'red' (works for both tables).

Note that there is a space between tr and :nth-child(3), and no td in front of :nth-child(3).

You can check out this site for sample code and experiment with it.

M4N
ah! a space. Big difference between 'tr:nth-child()' and 'tr :nth-child()'! That helps!
DA