Search code examples
jqueryrecursiondom-traversal

How to write a simple preorder DOM tree traversal algorithm in jQuery?


I'd like to take the code found here: http://www.jslab.dk/articles/non.recursive.preorder.traversal.part2

// HTML element
var root = document.documentElement;

recursivePreorder(root);

// Recusively find and handle all text nodes
function recursivePreorder(node) {  
  // If node is a text node
  if (node.type == 3) {
    // Do something with node
  }
  // else recurse for each child node
  else {
    for(var i=0; i<node.childNodes.length; i++)
      recursivePreorder(node.childNodes[i]);
  }
}

and convert it into clean jQuery.

Any idea? I know recursion requires argument.callee since the callbacks in jQuery are anonymous, but I'm too new to JQuery to take it any further.

Thanks!


Solution

  • As Code Duck pointed out, jQuery traverses nodes in source-order, depth-first - or, as you call it, pre-order. However, contents only gets immediate children nodes, not descendants. Try this:

    $(document).contents ().each (function processNodes ()
    {
        if (this.nodeType == 3)
            doSomething (this); // do something with text node
        else
            $(this).contents ().each (processNodes);
    });
    

    As an aside, arguments.callee is marked for deprecation, hence the named (as opposed to anonymous) function