Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an in-order traversal of the DOM? [closed]

Tags:

javascript

I found this ridiculously technical document:

http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-Document

but did not see how it related to writing actual JavaScript code.

I would guess that I could use basic DOM methods and properties like eachChild() and .children to do the traversal, but I'm not sure what the best strategy is?

like image 769
Handy Avatar asked Dec 16 '22 07:12

Handy


2 Answers

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);
});
like image 162
bfavaretto Avatar answered Jan 03 '23 13:01

bfavaretto


Here is one way to do this using document.createNodeIterator:

var nodeIterator = document.createNodeIterator(document.body);
var currentNode;
while (currentNode = nodeIterator.nextNode()) {
    console.log(currentNode);
}
like image 45
Andrew Clark Avatar answered Jan 03 '23 13:01

Andrew Clark