jQuery Traversal - eq() Method
Example
By adding an appropriate class to the div at index 2, it is turned blue:
$("body").find("div").eq(2).addClass("blue");
Definition and Usage
The eq() method reduces the set of matched elements to one at the specified index.
Syntax
.eq(index)
Parameter | Description |
---|---|
index |
Integer, indicating the position of the element (minimum is 0). If negative, it counts back from the last element in the collection. |
Detailed Description
If a jQuery object representing a collection of DOM elements is given, the .eq() method will construct a new jQuery object with one element from the collection. The index parameter used indicates the position of the element in the collection.
Please see the following simple list:
<ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
Example 1
We can apply this method to this collection of list items:
$('li').eq(2).css('background-color', 'red');
The result of this call sets the red background for item 3. Note that the index is zero-based and refers to the position of the element in the jQuery object, not in the DOM tree.
Example 2
If a negative number is provided, it indicates the position from the end of the collection, not from the beginning. For example:
$('li').eq(-2).css('background-color', 'red');
This time, the background of item 4 turns red because it is the second from the end of the collection.
Example 3
If the element cannot be found based on the specified index parameter, this method constructs a jQuery object with an empty set, and the length property is 0.
$('li').eq(5).css('background-color', 'red');
Here, no list item will turn red because the .eq(5) indicates the sixth list item.