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
5 answers
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