Use javascript to count immediate child elements of an element

廉价感情. 提交于 2019-11-27 22:16:38

问题


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.

The jQuery equivalent would be:

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

But I need to do this javascript only.


回答1:


Use the DOM selector interface (querySelectorAll).

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

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


来源:https://stackoverflow.com/questions/5685184/use-javascript-to-count-immediate-child-elements-of-an-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!