The jQuery Eq method is used to select elements by their index. The index in jQuery always starts with 0.
1 | $(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.
There is a div that contains 4 p elements. To selected the 3rd p element I will pass 2 to the jQuery Eq Method.
1 2 3 4 5 6 7 8 | < 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.
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:
1 | $( "#div1 p" ).eq(-1).css( "background-color" , "purple" ); |
Check the below link:
1. jQuery fadeIn & fadeOut Methods
2. How to use jQuery Toggle Method – .toggle()