Recursion Down Dom Tree

This is code from Crockford's JavaScript: The Good Parts.

var results = [];

var walkDOM = function (node,func) {
        func(node);                     //What does this do?
        node = node.firstChild;
        while(node) {
            walkDOM(node,func);
            node = node.nextSibling;
        }

    };

I understand the code except for func(node). I guess the point is to pass node as a parameter in function func, but how will the browser understand it this way? node and func could be anything--so when the function is called it could read like this:

walkDOM(document.body,function(att) {
          node.getAttribute(att);
          results.push(node);
          });

When func is passed, walkDOM will process function(att) {...}(document.body)--which wouldn't make any sense. So why has Crockford chosen to include func(node)?

6

4 Answers

Yes this tree traversal function makes sense since :

  • the function argument is supposed to know how to handle (any) nodes
  • the first call argument is supposed to be a supported node (not document.body for instance, if func doesn't know how to handle it)

That said, this algorithm still looks incorrect to me, as it only explores through the first sibling ; other siblings will be simply ignored. So I would recommend using this more traditional approach instead :

function walk(node, func) {
   var children = node.childNodes;
   for (var i = 0; i < children.length; i++)  // Children are siblings to each other
       walk(children[i], func);
   func(node);
}

Note that version is "deep first" (i.e. not calling call func() before processing children), but I'd rather recommend it since func is likely to change nodes. This way the processing of a parent will be able to consider the latest state of its already-processed children before issuing possibly un-appropriate changes.

Looks to me like the func is used for doing something to every node in the tree.

For example, if I wanted to alert the tag name for every node in the entire tree:

walkDOM(document.body, function(node) {
    alert(node.tagName);
});

In your example function:

walkDOM(document.body,function(att) {
      node.getAttribute(att);
      results.push(node);
      });

... you have named the node parameter to att, but that doesn't magically make in a name of an attribute. I would expect a "variable 'node' is not defined" when node.getAttribute(att) is ran, because node is being set to att... there is no node in that function's scope.

The func that's in the

func(node)

line is what is typically known as a callback function. It a function that is available for use by the walkDOM function. It might make sense with a more verbose function name:

var results = [];

var walkDOM = function (node, iCanBeCalledOnANode) {
    iCanBeCalledOnANode(node); // Will be called on every DOM element 
    node = node.firstChild;
    while(node) {
        walkDOM(node,func);
        node = node.nextSibling;
    }

};

Hope this clears things up for you.

Crockford's code is passing a callback to walkDOM which can be used in many ways to process the arguments passed to it.

An example could be a method which returns the count of all DOM elements with the specified tagName:

var getTagNameCount = function(tagName) {
    var count = 0;
    walkDOM(document.body, function(node) {
       if (node.tagName === tagName) {
          count++;
       }
    });
    return count;
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest