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?
Implementing an algorithm that walks the DOM without recursion
javascript;recursion;dom;iteration
How about something like this?function iterate() {    var ch = document.body;    while (ch) {        //if node has children, get the first child        if (ch.children.length > 0) {            ch = ch.firstElementChild;        //if node has silbing, get the sibling        } else if (ch.nextElementSibling) {            ch = ch.nextElementSibling;        //if it has neither, crawl up the dom until you find a node that has a sibling and get that sibling        } else {            do {                ch = ch.parentNode;                //if we are back at document.body, return!                if (ch === document.body) {                    return;                }            } while (!ch.nextElementSibling)            ch = ch.nextElementSibling;        }        console.log(ch.id);    }}iterate();FIDDLE