In jQuery, what are some of the key differences between using :eq() and :nth-child() to select any elements ?
Also in general, for the starting index, in which case does it start from "0" and when it starts from "1" ?
In jQuery, what are some of the key differences between using :eq() and :nth-child() to select any elements ?
Also in general, for the starting index, in which case does it start from "0" and when it starts from "1" ?
eq() starts with 0, while nth-child() starts with 1
see differences clearly here http://jsfiddle.net/9xu2R/
CSS :first-child, :nth-child, and :last-child are not like :eq
So if we had a snippet of HTML like
Then the selector .foo:nth-child(2)will match the div #bar2. If we insert another element at the front of the container:
And again we select .foo:nth-child(2), we match the div #bar1 because the 2nd child of the container also matches .foo.
Thus, in this second example, if we try .foo:nth-child(1) or the equivalent .foo:first-child, we will not match any elements because the first child element in that container — the p tag — does not match .foo.
Likewise, :nth-child can match children in multiple containers. In the HTML snippet:
the selector .foo:last-child will match the divs #bar3 and #quux; but .foo:first-child or .foo:nth-child(1) will only match #quux because the first child of the first container is, again, not a .foo.
Source https://content.pivotal.io/blog/css-first-child-nth-child-and-last-child-are-not-like-eq
:eq()
:nth-child()
Further discussion of this unusual usage can be found in the W3C CSS specification.
Detailed Comparision
See the Demo: http://jsfiddle.net/rathoreahsan/sXHtB/ -- Link updated
Also See the references
http://api.jquery.com/eq-selector/
http://api.jquery.com/nth-child-selector/
:eq
is array indexed based, so it starts from 0. It is also not part of the Css specification.Whereas
:nth-child
is part of the Css specification and refers to the element position in a DOM tree.In terms of usage, they both do the same thing.
Demo here
:eq()
allows you to access the elements in the jQuery object by indexhttp://api.jquery.com/eq-selector/
:nth-child
also allows you to access the an element by index, however it only applies to the term to the immediate left of it.http://api.jquery.com/nth-child-selector/
This means that if you want to pick one element from a selector then use :eq if you want to restrict selections to elements with n-1 preceding-sibilings then use nth-child.
Javascript arrays are usually indexed from 0; however nth-child is indexed from 1 because it is technically a CSS property as opposed to a jQuery one.
See: http://api.jquery.com/eq-selector/ and http://api.jquery.com/nth-child-selector/
Good luck.