Javascript 如何使用javascript计算另一个div内的div总数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2249693/
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
how to count total number of divs inside another div using javascript
提问by Gabriele Petrioli
How to count the total number of divelements that are contained in another divusing javascript?
如何使用javascript计算div另一个包含的元素总数div?
回答by Gabriele Petrioli
The getElementsByTagName()is not only a documentmethod, but one that can run on any DOM element.
这getElementsByTagName()不仅是一种document方法,而且可以在任何 DOM 元素上运行。
element.getElementsByTagNameis similar to document.getElementsByTagName, except that its search is restricted to those elements which are descendants of the specified element
元素。getElementsByTagName类似于 document。getElementsByTagName,除了它的搜索仅限于指定元素的后代元素
see more at https://developer.mozilla.org/en/DOM/element.getElementsByTagName
在https://developer.mozilla.org/en/DOM/element.getElementsByTagName查看更多
So the actual code that does what you ask is
因此,执行您要求的实际代码是
var container_div = document.getElementById('id_of_container_div');
var count = top_level_div.getElementsByTagName('div').length;
回答by David Salamon
You can use @davidcmoulton's handy Gist: https://gist.github.com/davidcmoulton/a76949a5f35375cfbc24
您可以使用@davidcmoulton 的方便 Gist:https://gist.github.com/davidcmoulton/a76949a5f35375cfbc24
I find it quite useful that it doesn't only count DIVs but also lists the count of all element types of your page.
我发现它非常有用,它不仅可以计算 DIV,还可以列出页面所有元素类型的数量。
Here is a copy of the Gist for further reference:
这是 Gist 的副本以供进一步参考:
(function (window, undefined) {
// Counts all DOM elements by name & logs resulting object to console.
var forEach = Array.prototype.forEach,
counter = {},
incrementElementCount = function (elementName) {
if (counter.hasOwnProperty(elementName)) {
counter[elementName] += 1;
} else {
counter[elementName] = 1;
}
},
processNode = function (node) {
var currentNode = node;
if (currentNode.nodeType === currentNode.ELEMENT_NODE) {
incrementElementCount(currentNode.nodeName);
if (currentNode.hasChildNodes) {
forEach.call(currentNode.childNodes, function (childNode) {
if (childNode.nodeType === currentNode.ELEMENT_NODE) {
processNode(childNode);
}
});
}
}
};
processNode(window.document.firstElementChild);
console.log(counter);
}(this));
回答by user1972007
There are many way to count divs element using jquery.
有很多方法可以使用 jquery 计算 divs 元素。
But most popular and simple way are:
但最流行和最简单的方法是:
$(document).ready(function(){
var divCount = $("div").size();
alert(divCount);
});
AND
和
$(document).ready(function(){
var divCount = $("div").length;
alert(divCount);
});
Its helpful for you
它对你有帮助

