Javascript - child node count

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);

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

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

Tags:

Javascript

Dom