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 versionway of writing this without recursion?