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

问题描述:

我可以获取元素的所有后代的计数,但是我似乎无法仅定位 子元素。这是我目前的情况。

I can get the count of all descendants of an element, but I can't seem to target just the immediate children. 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.

jQuery等效项为:

The jQuery equivalent would be:

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

但是我只需要做这个javascript。

But I need to do this javascript only.

使用DOM选择器界面( querySelectorAll )。

Use the DOM selector interface (querySelectorAll).

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

如果你想要一个向后兼容的解决方案,循环 childNodes 和count个元素节点。

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

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++;
    }
}