a
  • b
  • c

    Jquery get index / position of sibling example

    Say I have the following html

    <ul> <li id="a">a</li> <li id="b">b</li> <li id="c">c</li> </ul> <ul> <li id="d">d</li> <li id="e">e</li> <li id="f">f</li> </ul> 

    If I used jQuery to grab the $ ('# e') element, how do I determine the position of the position / index e relative to my siblings d and f? In other words, I expect that the value 1 (if the index is based on zero) will be returned, or 2 (if the index is one), because this is the second element in the ul list.

    +6
    source share
    5 answers

    Simple: var idx = $('#e').index() // zero based

    +16
    source

    You can use .index() to get an index based on the zero of an element relative to your siblings.

     $('#e').index(); 

    http://jsfiddle.net/LXS9F/

    +2
    source

    You can also try the following:

     $(function() { $('ul li').each(function(idx, e) { $(this).on('click', function() { alert(idx); }); }); }); 

    The only problem is that it will index all li on the whole page.

    Edit

    This gives an index of the entire contents of li .

     $(function() { $('ul li').each(function(idx, e) { $(this).on('click', function() { alert($('#' + $(this).attr('id')).index()); }); }); }); 
    +1
    source

    You can also use var idx = $("#e").prevAll().size()

    +1
    source
     function getIndex(id) { $('ul > li').each(function() { if ($(this).attr('id') == id) { return i; } }); return 0; } 
    0
    source

    Source: https://habr.com/ru/post/928086/


    All Articles