How to Select an Element by Index Using jQuery eq()
The jQuery .eq() method allows developers to select a
specific DOM element from a matched set based on its numerical index.
This article covers the syntax of the .eq() method,
demonstrates how zero-based and negative indexing work, and explains how
to manipulate the selected element within your JavaScript code.
Syntax and Basic Usage
The .eq() method constructs a new jQuery object
containing the single element located at the specified index position
within the original collection.
The syntax is:
$(selector).eq(index);The index argument is an integer indicating the position
of the element. Because jQuery uses zero-based indexing, the first
element in the matched set has an index of 0, the second
element has an index of 1, and so on.
Selecting by Positive Index
To target an element from the beginning of a collection, provide a
positive integer starting at 0.
Consider the following HTML list:
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
<li>Date</li>
</ul>To select "Banana" (the second item) and change its text color, pass
1 into the .eq() method:
$('li').eq(1).css('color', 'yellow');Selecting by Negative Index
The .eq() method also accepts negative integers, which
count backward from the end of the collection. An index of
-1 selects the last element, -2 selects the
second-to-last element, and so forth.
Using the same HTML list, you can target "Date" (the last item) like this:
$('li').eq(-1).addClass('highlight');To target "Cherry" (the second-to-last item):
$('li').eq(-2).addClass('highlight');.eq() Method vs.
:eq() Selector
jQuery also provides a :eq() pseudo-class selector
(e.g., $('li:eq(1)')). While both achieve similar results,
using the traversing method $('li').eq(1) is generally
preferred. The method version allows jQuery to use native DOM querying
via querySelectorAll first, resulting in better performance
compared to the custom Sizzle pseudo-class selector.