Wednesday, 20 July 2011

jQuery eq(index) method

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

index is an integer indicating the 0-based position of the element.When index is a -ve value, counting is done backwards from the last element in the set.

Consider a page with a simple list on it:

<ul>
<li>list item 1
<li>list item 2
<li>list item 3
<li>list item 4
<li>list item 5
</ul>

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

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

he 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:

$('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.

No comments:

Post a Comment