Traversing DOM (sub)trees with a recursive "walk the DOM" function.

This function traverses a DOM (sub)tree and executes a given function on each Element and Text node it visits.

function walkTheDOM(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walkTheDOM(node, func);
        node = node.nextSibling;
    }
}

// Example usage: Process all Text nodes on the page
walkTheDOM(document.body, function (node) {
    if (node.nodeType === 3) { // Is it a Text node?
        var text = node.data.trim();
        if (text.length > 0) { // Does it have non white-space text content?
            // process text
        }
    }
});
Published: 6/26/2013
Author: Douglas Crockford
Source: http://www.youtube.com/watch?v=Y2Y0U-2qJMs&feature=youtu.be&t=27m15s
Tags: dom
comments powered by Disqus