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?
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);
});
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With