Description: Reduce the set of matched elements to the one at the specified index.
.eq( index )
version added: 1.1.2
index
An integer indicating the 0-based position of the element.
.eq( -index )
version added: 1.4
-index
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 of the matching elements. The supplied index identifies the position of this element in the set.
Consider a page with a simple list on it:
<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:
$('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.
- list item 1
- list item 2
- list item 3
- list item 4
- list item 5
If a negative number is provided, this indicates a position starting from the end of the set, rather than the beginning. For example:
$('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.
- list item 1
- list item 2
- list item 3
- list item 4
- list item 5
Examples
Example 1
Turn the div with index 2 blue by adding an appropriate class.Full source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("div").eq(2).addClass("blue");
});
</script>
<style>
div { width:60px; height:60px; margin:10px; float:left;
border:2px solid blue; }
.blue { background:blue; }
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
Was this information helpful?

