Search code examples
javascripthtmltreepreorder

Inorden route html with javascript


how to make a pre-order traversal of elements in a html tree with javascript

enter image description here

Img src = http://www.sitepoint.com/hierarchical-data-database-2/ (Great Article) ,assume that boxs are a html element

example:

function preorderHtml(element patern)
{
 //preorder tree traversal

}

Solution

  • function traversePreorder(el, indent) {
      indent = (indent || '')
      console.log(indent + el.nodeName); // Do something with the element here...
      for (var i=0; i<el.children.length; i++) {
        traversePreorder(el.children[i], indent + '  ');
      }
    }
    traversePreorder(document.body);
    

    I would probably introduce a second argument which is a function that gets called at each element so that this method could be reused.

    function traversePreorder(el, func, indent) {
      indent = (indent || '')
      func(el);
      //...
    }
    traversePreorder(document.body, function(element) {
      console.log(el.nodeName); // Do something here...
    });