Use javascript to count immediate child elements of an element

前端 未结 1 1722
醉酒成梦
醉酒成梦 2020-12-16 18:10

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.

va         


        
相关标签:
1条回答
  • 2020-12-16 18:26

    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++;
        }
    }
    
    0 讨论(0)
提交回复
热议问题