简体   繁体   中英

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, ie first, second or third?

You can achieve this with an each loop and then you look up if the item element has a bigger length than 0. Please note that the counter starts at 0.

I made you an example which alerts the index of the element that contains something. If you want to start counting at 1 just write index+1 within the alert.

$(".box").each(function(index){
    if($(this).children(".item").length > 0){
      alert(index);
    }
});

https://jsfiddle.net/m1voxk6e/

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> 

Try this :

$(".box").each(function(index,ele){

    if($(this).children().length > 0)

        alert("Div Number "  + (index + 1) + " have Item(s)");

})

Final code :

 <!DOCTYPE html> <html lang="en"> <head> </head> <body> <div class="box"> </div> <div class="box"> <span class="item">my item</span> </div> <div class="box"> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $(".box").each(function(index,ele){ if($(this).children().length > 0) alert("Div Number " + (index + 1) + " have Item(s)"); }) </script> </body> </html> 

you could use the length property of the object

Ex:

 $(document).ready(function(){ var obj=$(".box").children('.item'); if(obj.length>0){ //do something with the object alert(obj.parent().html()); alert(obj.parent().index()); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="box"> </div> <div class="box"> <span class="item">my item</span> </div> <div class="box"> </div> 

You can use :has() or .has() to selecting .box element contain .item .

$(".box:has(.item)").index(".box");
// Or
$(".box").has(".item").index(".box");

 var index = $(".box:has(.item)").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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM