Here's a simple algorithm that walks the DOM given a node:
function walkDOM(n) {
do {
console.log(n);
if (n.hasChildNodes()) {
walkDOM(n.firstChild)
}
} while (n = n.nextSibling)
}
I wanted to implement it iteratively as an exercise, and came up with this:
function walkDOM2(n) {
var recStack = [];
// First get the parent of the given node, so that
// you can get the siblings of the given node too
// (starting from the last sibling),
// rather than just start with the children of the
// given node.
// (This is to make this behave the
// same way as the recursive one.)
recStack.push(n.parentNode);
while (recStack.length > 0) {
var current = recStack.pop();
// Log only if the current node is
// the given node or a node below it.
// (This is to make this behave the
// same way as the recursive one.)
if (current != n.parentNode)
console.log(current);
if (!current.hasChildNodes())
continue;
current = current.lastChild;
do {
recStack.push(current);
// Skip the sibling nodes
// before the given node.
// (This is to make this behave the
// same way as the recursive one.)
if (current === n)
break;
} while (current = current && current.previousSibling);
}
}
I have used a couple tricks to make it behave the same way as the first recursive version. Is there a more concise way of writing this without recursion?