jQuery :nth-child() Selector
Learn all about the jQuery function :nth-child() Selector.
Because jQuery’s implementation of :nth-
selectors is strictly derived from the CSS specification, the value of n
is "1-indexed", meaning that the counting starts at 1. For other selector expressions such as :eq()
or :even
jQuery follows JavaScript’s "0-indexed" counting. Given a single <ul>
containing two <li>
s, $( "li:nth-child(1)" )
selects the first <li>
while $( "li:eq(1)" )
selects the second.
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 (n+1)th one (n is 0-based) is selected.
Further discussion of this unusual usage can be found in the W3C CSS specification.