.eq()


.eq( index )Returns: jQuery

Description: Reduce the set of matched elements to the one at the specified index.

  • version added: 1.1.2.eq( index )

    • index
      Type: Integer
      An integer indicating the 0-based position of the element.
  • version added: 1.4.eq( indexFromEnd )

    • indexFromEnd
      Type: Integer
      An integer indicating the position of the element, counting backwards from the last element in the set.

Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.

Consider a page with a simple list on it:

1
2
3
4
5
6
7
<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>

We can apply this method to the set of list items:

1
$( "li" ).eq( 2 ).css( "background-color", "red" );

The result of this call is a red background for item 3. Note that the supplied index is zero-based, and refers to the position of the element within the jQuery object, not within the DOM tree.

Providing a negative number indicates a position starting from the end of the set, rather than the beginning. For example:

1
$( "li" ).eq( -2 ).css( "background-color", "red" );

This time list item 4 is turned red, since it is two from the end of the set.

If an element cannot be found at the specified zero-based index, the method constructs a new jQuery object with an empty set and a length property of 0.

1
$( "li" ).eq( 5 ).css( "background-color", "red" );

Here, none of the list items is turned red, since .eq( 5 ) indicates the sixth of five list items.

Example:

Turn the div with index 2 blue by adding an appropriate class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>eq demo</title>
<style>
div {
width: 60px;
height: 60px;
margin: 10px;
float: left;
border: 2px solid blue;
}
.blue {
background: blue;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
$( "body" ).find( "div" ).eq( 2 ).addClass( "blue" );
</script>
</body>
</html>

Demo: