JavaScript DOM traversal and printing the DOM.

Just messing around with DOM in JavaScript and printing the DOM with things like NodeIterator and TreeWalker

by Augustus Yuan

HTML

<div id="dom-selector">
  <div>
    <div>
      <div>
        Hello!
      </div>
    </div>
    <span>Yo!</span>
  </div>
  <h1>Harro!</h1>
</div>

<div id="result"></div>

JavaScript

function printDomNodes(node) {
	if (node.childNodes && node.childNodes.length > 0) {
  	for (var i=0; i < node.childNodes.length; i++) {
    	printDomNodes(node.childNodes[i]);
    }
  } else {
		console.log(node);
  }
}

function printDomNodesWithNextSibling(node) {
  var el = node.nextSibling;
  var i = 1;
  while (el) {
    console.log(i + '. ' + el.nodeName);
    el = el.nextSibling;
    i++;
  }
}


function nodeIteratorTraversal(root) {
  var iter = document.createNodeIterator(
          root, NodeFilter.SHOW_ELEMENT, null);

  while (n = iter.nextNode()) {
    console.log(n);
  }
}

// printDomNodes(document.getElementById('dom-selector'));
(function() {
	nodeIteratorTraversal(document.getElementById('dom-selector'));
  printDomNodesWithNextSibling(document.getElementById('dom-selector'));
})();