santa santa - 2 months ago 10
HTML Question

How to get index of element has specific child using jquery?

I have three div containers.

<div class="box"></div>
<div class="box">
<span class="item">my item</span>
</div>
<div class="box"></div>


There's an item in one of the containers. How do I detect which container it is, i.e. first, second or third?

Answer

There's no need for a loop here, you can simply get the index() of the .box that contains the .item by selecting it directly:

var index = $('.box .item').closest('.box').index('.box');
console.log(index);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box">
  <span class="item">my item</span>
</div>
<div class="box"></div>