DOM Tree Walker as an exercise[JS]
<p>Write a function called nextNode that can be used to walk through all the nodes of a DOM tree. The function should take a node as an argument, and return the next node in the tree. For example, the following loop would visit every node once, and only once:</p>

<pre><code> var node = document.body;
  do {
    node = nextNode(node);
  } while (node != null)
</code></pre>

<p>I think from DOM it's supposed to only use <code>firstChild, lastChild, previousSibling, nextSibling,</code> and <code>parentNode</code>.</p>

<p>Code below should be how i imagine it to work. The problem is with the childNodes, seems like it needs a for/while loop to work. But the loop needs to somehow remember the last childNodes position and add i+1 because of it's call in do/while loop. I don't know what condition to give there and i get infinite loops.</p>

<pre><code>nextNode = function(node) {
  // for/while loop?
  if (node.childNodes) {
  }
  else if (node.nextSibling) {
    node = node.nextSibling;
  }
  else {
    node = node.parentNode.nextSibling;
  }
  return node;
};
</code></pre>

<p>Unless i'm completely wrong about it. Could someone elaborate or point me in the right direction?</p>