Tan Kucukhas Tan Kucukhas - 27 days ago 13
jQuery Question

Get index value of nested list item with jQuery

I'm trying to get the index value of an nested

li
item once I click on the item itself.

As you can see on the console I could get the index values of the items that are not nested properly but the nested once are giving me 0 or 1 instead of 2 or 3, naturally.

Is there a way I could find the index value of the
li
even though its inside another div within the
ul
?



$('li a').on('click', function() {
console.log($($(this)["0"].offsetParent).find('li') );
console.log($(this).parent().index() )
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#">Item 0</a></li>
<li><a href="#">Item 1</a></li>
<div class="group">
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</div>
<li><a href="#">Item 4</a></li>
</ul>




Answer

You are using index() property in a wrong way, try this code.

$('li a').on('click', function() {
  console.log( $(this).index("a") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Item 0</a></li>
  <li><a href="#">Item 1</a></li>
  <div class="group">
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a></li>
  </div>
  <li><a href="#">Item 4</a></li>
</ul>