$('table td:eq(2) a')
return the a
tag of the third column but only from the first row.
Why?
Select the first row in a table $("tr:first") 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).
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.
$('table td:eq(2)') will select all 'table td' , and the index eq(2) will select the third td from this collection.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With