Search code examples
javascriptnodelistchild-nodes

Recurse over childNodes


Take a look at the code below, with the console open. There are a handful of nodes logged to the console.

function recurseChildren(element) {
  var children = element.childNodes,
    length = children.length;

  if (length) {
    for (var i = 0; i < length; i++) {
      console.dir(children[i]);
      recurseChildren(children[i]);
    }
  }
}

recurseChildren(document.body);

Then run this in the console: document.body.childNodes.length;

There's 23 logged at that point.

Shouldn't the recurseChildren() function do a console.dir of a whole lot of items?


Solution

  • These are two different environments. You're running the script from stackoverflow's editor and then running document.body.childNodes.length in your console for the site. stackoverflow's editor is constrained to an iframe with minimal code. If you open your console and view the output after running this script, you'll notice that it isn't 23 but 2 or thereabouts (running document.body.childNodes.length in my console for SO gave me 25).

    console.log(document.body.childNodes.length);
    document.write('total nodes in this iframe: ' + document.body.childNodes.length);