Difference Between jQuery :nth-child and :eq()
While both the :nth-child and :eq()
selectors in jQuery allow developers to target elements based on their
numerical position, they operate under fundamentally different rules.
The primary differences lie in their indexing systems, how they scope
elements within the Document Object Model (DOM), and whether they comply
with standard CSS specifications. Understanding these distinctions
ensures you select the exact elements you intend without unexpected
layout bugs or performance issues.
1. Index Base: 1-Based vs. 0-Based
The most immediate difference is the way each selector counts:
:nth-child(n)is 1-indexed. Following CSS conventions, counting starts at1. To select the first element, you use:nth-child(1).:eq(n)is 0-indexed. Following JavaScript array conventions, counting starts at0. To select the first element, you use:eq(0).
2. Selection Scope: Sibling Context vs. Global Matched Set
The most significant functional difference is how the selectors evaluate the DOM tree:
:nth-child()evaluates elements relative to their siblings. It checks an element's position among its siblings under the same parent element. If your page has multiple parent containers matching the selector,:nth-child()will return an element from each parent container.:eq()evaluates elements within the jQuery collection. It filters the entire flattened set of elements matched by the preceding selector, regardless of where they reside in the DOM hierarchy. Consequently,:eq()always returns at most one single element.
Example Scenario
Consider the following HTML markup:
<ul id="list-a">
<li>Item A1</li>
<li>Item A2</li>
</ul>
<ul id="list-b">
<li>Item B1</li>
<li>Item B2</li>
</ul>- Running
$('li:nth-child(1)')selects both Item A1 and Item B1, because each is the first child of its respective parent<ul>. - Running
$('li:eq(0)')selects only Item A1, because it is the first element in the overall jQuery collection of all<li>elements on the page. - Running
$('li:eq(2)')selects Item B1, which is the third element (index 2) in the combined list.
3. Native CSS Support vs. jQuery Extension
:nth-childis a native CSS selector. Because it is part of the official W3C CSS specification, modern browsers can process it directly using the nativequerySelectorAllAPI, resulting in faster execution. It can also accept keywords and algebraic formulas (e.g.,:nth-child(odd),:nth-child(2n+1)).:eq()is a proprietary jQuery selector. It is not part of the CSS specification. Because browsers do not natively understand:eq(), jQuery must parse and evaluate the selector using its own JavaScript engine (Sizzle), which incurs a slight performance penalty on large DOM trees. For better performance when using index-based filtering, jQuery provides the native.eq()method (e.g.,$('li').eq(0)), which allows the initial query to run via native browser methods before applying the filter.