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
3 Answers
Reset to default 6Use 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.item
s 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 );
});
本文标签:
版权声明:本文标题:javascript - jQuery count number of divs with a particular class inside a div with a particular class - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742395664a2466865.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论