admin管理员组

文章数量:1336142

How can I count the number of div's with class item that are inside the div with class outer-1? The result here should be 7.

I tried this and several other failed variations of it.

alert( $(".outer-1").$(".item").length );

This gives me 12 which is all the divs on the page. alert( $(".item").length );

How can i specify only the outer-1 div?

Divs

<div class="outer-1">
    <div class="item">a</div>
    <div class="item">b</div>
    <div class="item">c</div>
    <div class="item">d</div>
    <div class="item">e</div>
    <div class="item">f</div>
    <div class="item">g</div>
</div>

<div class="outer-2">
    <div class="item">a</div>
    <div class="item">b</div>
    <div class="item">c</div>
    <div class="item">d</div>
    <div class="item">e</div>
</div>

How can I count the number of div's with class item that are inside the div with class outer-1? The result here should be 7.

I tried this and several other failed variations of it.

alert( $(".outer-1").$(".item").length );

This gives me 12 which is all the divs on the page. alert( $(".item").length );

How can i specify only the outer-1 div?

Divs

<div class="outer-1">
    <div class="item">a</div>
    <div class="item">b</div>
    <div class="item">c</div>
    <div class="item">d</div>
    <div class="item">e</div>
    <div class="item">f</div>
    <div class="item">g</div>
</div>

<div class="outer-2">
    <div class="item">a</div>
    <div class="item">b</div>
    <div class="item">c</div>
    <div class="item">d</div>
    <div class="item">e</div>
</div>
Share Improve this question asked Sep 7, 2014 at 15:40 NormanNorman 6,36526 gold badges91 silver badges148 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Use find() selector:

$(".outer-1").find(".item").length ;

or

 $(".outer-1 .item").length 

For your html, $(".outer-1 .item").length would be sufficient, but if div.items are nested, like this

<div class="outer-1">
    <div class="item">a</div>
    <div class="item">b</div>
    <div class="item">c</div>
    <div class="item">d</div>
    <div class="outer-x">
      <div class="item">h</div>
      <div class="item">i</div>
    </div>
    <div class="item">e</div>
    <div class="item">f</div>
    <div class="item">g</div>
</div>

You may want to use $(".outer-1 > .item").length (all div.item that are child of div.outer-1).

See jsFiddle

if you have a bunch of outers with the same name, you may need to loop:

$('.outer-1').each(function(){
   console.log( $('.item',this).length );
});

本文标签: