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

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

Why?

+4
source share
4 answers

This is not a mistake, but it is definitely confusing. Which will give you the result you expect:

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

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

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

The nth-child (n) pseudo-class is easily confused with: eq (n), although the two can lead to completely different matched elements. Using nth-child (n), all child elements are taken into account, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. Using: eq (n), only the selector attached to the pseudo-class is counted, not just the children of any other element, and the nth is selected.

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

+6
source

No, this is not a mistake. It matches the anchor tag in the third element in the set, which corresponds to table td , so it is 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.)

+3
source

Simple word

According to your code, $('table td:eq(2)') returns the third td in the table as strting from index = 0, it will select the third td below

enter image description here

for $('table td:eq(4)') result will be the fifth td in the table below

enter image description here

to choose to use the entire second column: the nth-child () index starts at 1

ex: $('table td:nth-child(2)')

enter image description here

I hope you get an answer.

+2
source

$('table td:eq(2)') will select all 'table td' , and index eq(2) will select the third td from this collection. therefore, there is only one a in the third column.

0
source

Source: https://habr.com/ru/post/1300250/


All Articles