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.

Related method: To select a nth child of a parent element use jQuery nth child method. The value of ‘n’ should be a positive integer specifying which number of child you want to select.

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");

Check the below link:

DOWNLOAD

2 important jQuery tutorials which you should read are:

1. jQuery fadeIn & fadeOut Methods
2. How to use jQuery Toggle Method – .toggle()

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate