jQuery index() method – Get the index of an element relative to its siblings

jQuery index() method – Get the index of an element relative to its siblings

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.

Example of jQuery Index Method

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.

Syntax of jQuery Index Method

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

jquery Index – Get the Index relative to an element.

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:

DOWNLOAD

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

Leave a Reply

Your email address will not be published. Required fields are marked *