Javascript - child node count

前端 未结 4 1979
甜味超标
甜味超标 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<m; i++) 
         if (children[i].nodeType===document.ELEMENT_NODE) 
             count++;
      return count;
    }
    console.info(countElements (children));​ // 3
    

    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
    
    0 讨论(0)
  • 2020-12-14 17:35

    If you want to get a list of all nested DOM nodes, you can use this code snippet:

    function getNestedElements(node) {
      const elems = [];
      const children = node.childNodes;
    
      for (let i = 0; i < children.length; i++) {
        if (children[i].nodeType === document.ELEMENT_NODE) {
          elems.push(children[i], ...getNestedElements(children[i]));
        }
      }
      return elems;
    }
    

    This is a modified version of @julien-ch answer

    0 讨论(0)
  • 2020-12-14 17:46

    childNodes returns the 3 list items, their text content and the whitespace between them (not in all browsers, though). Three alternatives:

    1. FF and Chrome: elem.childElementCount (will return 3)

    2. IE (&& FF AFAIK): elem.childNodes.length (===3)

    3. Old IE: elem.children.length

    0 讨论(0)
  • 2020-12-14 17:52

    childNodes gets all existing childNodes, including text nodes! In your example markup, you have your three "regular nodes" and 4 text nodes - the linebreaks - resulting in a total of 7 child nodes.

    What you instead want is .children.length or .childElementCount (not supported in IE<9) to only fetch "actual" nodes:

    let temp = document.getElementById('element').parentNode;
    console.log(temp.children.length);
    // or the following
    console.log(temp.childElementCount);
    
    0 讨论(0)
提交回复
热议问题