The jQuery Index method is very helpful in getting the index of an element relative to its siblings. For example – suppose there are few li elements inside a ul element and you have to find what’s the index of li that is clicked. In this condition you can use the .index() method of jQuery.
The page html code:
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
<li>forth</li>
</ul>
The jQuery .index() method code is:
$("li").click(function(){
alert($(this).index());
});
On clicking any of the li tag the alert box will show its index (relative to all the other 3 of its siblings).
Note – Index starts with 0. Here 0 for the first li and 3 for the last li.
$(selector).index(element);
Here “element” is an optional parameter, when provides the jQuery Index will provide the index relative to this “element”.
It will be more clear when you will see the below 2 examples.
There are 2 lists in ul li tag on an html page. There is also a button which on clicking will provide the index of li with id yogihosting relative to li element.
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
<li>forth</li>
</ul>
<ul>
<li>Google</li>
<li>Twitter</li>
<li id="yogihosting">YogiHosting</li>
<li>Facebook</li>
</ul>
<button id="index">Find Index</button>
$("#index").click(function (e) {
alert($("#yogihosting").index("li"));
});
When you click the button, the alert box will show 6 and not 2. This is because ($(“#yogihosting”).index(“li”) will provide the index relative to “li” element in the page.
There are 4 li tags in the first list, and these are also counted. This makes the index of li yogihosting 6.
<li>first</li> --- index 0
<li>second</li> --- index 1
<li>third</li> --- index 2
<li>forth</li> --- index 3
<li>Google</li> --- index 4
<li>Twitter</li> --- index 5
<li id="yogihosting">YogiHosting</li> --- index 6
<li>Facebook</li> --- index 7
You can download the source codes: