Here is a solution that is about as simpleconcise as your recursive solution. (8 lines of code.)
function walkDOM2(n) {
var stack = [n];
while (stack.length > 0) {
var node = stack.pop();
console.log(node);
stack = stack.concat(Array.prototype.slice.call(node.childNodes, 0).reverse());
}
}
Some notes on the above:
- After you pop an item off the end of the stack, you replace it with it's children.
- The children are reversed so that the first child is placed at the end of the stack, so it will be the next node to be popped.
- Use
Array.prototype.slice.call()
to turn thechildNodes
NodeList into an Array so it can be added to the stack withconcat
. - There is no
hasChildNodes()
check, but sometimes there will be no child nodes and an empty array will be added to the stack.