views:

583

answers:

2

$('table td:eq(2) a') return the a tag of the third column but only from the first row.

Why?

+3  A: 

No, it's not a bug. It matches the anchor tag in third element in the set matched by table td, so it's in the third cell in the table.

(If the table was only two cells wide, you would get the first cell in the second row.)

Guffa
That's OK. but Why the third cell in the second row doesn't include?
Mendy
as Guffa explained, table td get ALL the td elements in the table. Then eq(2) selects the 2nd one from the entire set.
Ben
@Guffa, @Ben thanks!
Mendy
+1  A: 

It is not a bug but it is definitely confusing. What will give you the result you expect is:

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

While :nth-child and :eq seem very similar the behavior can be quite different as can be seen from the result you expected.

The jQuery documentation on this can be found here. It states:

The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the nth one is selected.

In simpler words, eq(2) will select the third element in the while result set while :nth-child(3) will select the 3 child of its parent. And in this case the parent will be its tr.

Matthew Manela