Javascript 使用javascript计算元素的直接子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5685184/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:27:24  来源:igfitidea点击:

Use javascript to count immediate child elements of an element

javascriptjquerycountparent-child

提问by Ark-of-Ice

I can get the count of all descendants of an element, but I can't seem to target just the immediatechildren. Here's what I have at the moment.

我可以获得一个元素的所有后代的数量,但我似乎不能只针对直接的孩子。这是我目前所拥有的。

var sectionCount = document.getElementById("window").getElementsByTagName("section").length;

I've played with other stuff and different syntax, but I can't seem to get it.

我玩过其他东西和不同的语法,但我似乎无法理解。

The jQuery equivalent would be:

jQuery 等效项是:

var sectionCount = $("#window > section").length;

But I need to do this javascript only.

但我只需要做这个 javascript。

回答by Anurag

Use the DOM selector interface (querySelectorAll).

使用 DOM 选择器接口 ( querySelectorAll)。

var selectionCount = document.querySelectorAll("#window > section").length;

If you want a backwards compatible solution, loop through childNodesand count element nodes.

如果您想要一个向后兼容的解决方案,请循环遍历childNodes并计算元素节点。

var w = document.getElementById('window');
var count = 0; // this will contain the total elements.
for (var i = 0; i < w.childNodes.length; i++) {
    var node = w.childNodes[i];
    if (node.nodeType == Node.ELEMENT_NODE && node.nodeName == "SECTION") {
        count++;
    }
}