Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector $('table td:eq(2) a') get the cell only from the first row

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

Why?

like image 364
Fitzchak Yitzchaki Avatar asked Feb 04 '10 01:02

Fitzchak Yitzchaki


People also ask

How do I get the first row of a table in jQuery?

Select the first row in a table $("tr:first") in jQuery.

How can get TD value from table in jQuery?

jQuery: code to get TD text value on button click. text() method we get the TD value (table cell value). So our code to get table td text value looks like as written below. $(document). ready(function(){ // code to read selected table row cell data (values).

What is the difference between EQ () and get () methods in jQuery?

eq() returns it as a jQuery object, meaning the DOM element is wrapped in the jQuery wrapper, which means that it accepts jQuery functions. . get() returns an array of raw DOM elements. You may manipulate each of them by accessing its attributes and invoking its functions as you would on a raw DOM element.

What is TD EQ ()?

$('table td:eq(2)') will select all 'table td' , and the index eq(2) will select the third td from this collection.


1 Answers

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.

like image 174
Matthew Manela Avatar answered Nov 08 '22 00:11

Matthew Manela