Javascript - child node count

前端 未结 4 1978
甜味超标
甜味超标 2020-12-14 16:52
  • Array1
  • Array2
  • Array3
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 17:32

    The childrenNodes property include all types of nodes: TEXT_NODE, ELEMENT_NODE, COMMEN_NODE, etc....

    You need to count the number of elements, here is an example solution based on DOM that should work in all engines:

    var temp = document.getElementById('element').parentNode;
    var children = temp.childNodes;
    console.log(children.length); // 7
    
    function countElements(children) {
      var count=0;
      for (var i=0, m=children.length; i

    EDIT

    Similarly if you want a function to retrieve all children Elements only using DOM, here is a function:

    function childElements(node) {
      var elems = new Array();
      var children = node.childNodes;
    
        for (var i=0,i < children.length ; i++) {
             if (children[i].nodeType===document.ELEMENT_NODE) {
                 elems.push(children[i]);
                 return elems;
              }
             }
         }
    
    console.info(childElements(temp).length);​ //3
    

提交回复
热议问题