Select elements with their index using jQuery Eq Method – .eq()

Select elements with their index using jQuery Eq Method – .eq()

The jQuery Eq method is used to select elements by their index. The index in jQuery always starts with 0.

$(selector).eq(index)

The index can be positive or negative. Negative index will start from the end while positive index starts from 0.

If I provide -1 to the .eq(-1) then the last element will be selected.

Example 1: jQuery .eq(2)

There is a div that contains 4 p elements. To selected the 3rd p element I will pass 2 to the jQuery Eq Method.

<div id="div1">
    <p>First</p>
    <p>Second</p>
    <p>Third</p>
    <p>Fourth</p>
</div>
$("#div1 p").eq(2).css("background-color", "purple");

The above code will turn the 3rd p element purple.

Example 2: jQuery .eq(-1)

Now I can also use the negative integer values to select element from the end. So to change background color of the last element I can use the following code:

$("#div1 p").eq(-1).css("background-color", "purple");

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.