Once you get the root node, you only need firstChild
and nextSibling
. This is Douglas Crockford's function for that, from his book JavaScript - The Good Parts, p. 35:
var walk_the_DOM = function walk(node, func) {
func(node);
node = node.firstChild;
while(node) {
walk(node, func);
node = node.nextSibling;
}
}
It's meant to traverse the DOM from the given node, and run a callback on each node found. For example:
walk_the_DOM(document.body, function(node) {
console.log(node);
});