Javascript 统计<div>的个数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3522002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count the number of <div>
提问by user319854
Is it possible using jQuery to count the number of div elements?
是否可以使用 jQuery 来计算 div 元素的数量?
I have this code:
我有这个代码:
<div id = "center">
<div class ="name">text text</div>
<div class ="name">text text text ... </div>
<div class ="name">text ...</div>
</div>
And get number: 3
并获得数量:3
回答by Philippe Leybaert
$("#center div").lengthwill give you the count.
$("#center div").length会给你计数。
回答by Huthaifa Afanah
document.getElementsByTagName("div").lengthwill give you the desired answer
document.getElementsByTagName("div").length会给你想要的答案
回答by IgalSt
<div id = "center">
<div class ="name">text text</div>
<div class ="name">
<div class ="SomeOtherDiv">bla bla</div>
</div>
<div class ="name">text ...</div>
</div>
$('#center div').length // Result: 4
$('#center div').length // 结果:4
$('#center > div').length // Result: 3
$('#center > div').length // 结果:3

