javascript jQuery/JS - 计算元素内的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8598286/
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
jQuery/JS - Count elements within element
提问by TheCarver
In jQuery or JS I need to count the amount of DIV elements inside my parent DIV called cont
? I've seen similar questions here on StackOverflow and have tried the following.
在 jQuery 或 JS 中,我需要计算父 DIV 中的 DIV 元素数量cont
?我在 StackOverflow 上看到过类似的问题,并尝试了以下方法。
<div class="b-load" id="cont">
<div>
<img src="page2.jpg" alt=""/>
</div>
<div>
<img src="page3.jpg" alt="" />
</div>
<div>
<img src="page4.jpg" alt="" />
</div>
<div>
<img src="page5.jpg" alt="" />
</div>
</div>
function countPages() {
var maindiv = document.getElementById('cont');
var count = maindiv.getElementsByTagName('div').length;
alert(count);
}
The child DIV's are dynamically produced, so I need to count them after the page has finished loading. The problem I have is the function I wrote counts 13 DIV's and in this example, there should only 4!! Any help gratefully received..
子 DIV 是动态生成的,因此我需要在页面加载完成后对它们进行计数。我的问题是我写的函数有 13 个 DIV,在这个例子中,应该只有 4 个!!任何帮助感激地收到..
回答by Jake Feasel
console.log($("#cont div").length);
回答by Diode
var maindiv = document.getElementById('cont');
var count = maindiv.children.length;
alert(count);
回答by Bassam Mehanni
Try this
试试这个
$(function(){
var mainDiv = $('#cont');
var childDivCount = mainDiv.find('div').length;
});
By the way, this is jQuery's syntax (one of them anyways) for document ready. This will only fire after your page has completed loading.
顺便说一句,这是用于文档就绪的 jQuery 语法(无论如何都是其中之一)。这只会在您的页面完成加载后触发。
回答by Adrian
No need to use jQuery here. If you only need to know the amount of childElements, you can use node.childElementCount
这里不需要使用jQuery。如果您只需要知道 childElements 的数量,则可以使用node.childElementCount