title: Recursive function for going through unknown DOM
body: <p>I am learning about js <strong>DOM</strong> and I want to make a <strong>recursive function</strong> that I could use to <strong>go through all nodes in any DOM</strong>. I made it, but I can not figure out why my first attempt is not working:</p>
  
  <p><strong>HTML</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function mostrarNodosV2(node) {
    console.log(node.nodeName);
    if (node.firstElementChild != null) {
      node = node.firstElementChild;
      mostrarNodosV2(node);
    }
  
    if (node.nextElementSibling != null) {
      node = node.nextElementSibling;
      mostrarNodosV2(node);
    }
  
  }
  
  mostrarNodosV2(document);</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  
  &lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Exercise IV&lt;/title&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
    &lt;h1&gt; Just a header&lt;/h1&gt;
    &lt;p&gt;Nice paragraph&lt;/p&gt;
    &lt;ul&gt;
      &lt;li&gt;Im just an element list on an unordered list&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/body&gt;
  
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>The flow is next:</p>
  
  <ol>
  <li><strong>document node</strong>.</li>
  <li>we repeat the function with his first child: <strong>head node</strong>.</li>
  <li>we repeat the function with his first child: <strong>meta node</strong>.</li>
  <li>because of 'meta' has no childs, we repeat the function with his next
  sibling: <strong>title node</strong>.</li>
  <li>because of 'title' has no childs or next sibling, we end the
  function where node=title, we should end the function where node =
  meta, and we should continue checking the next sibling of head: <strong>body node</strong>.</li>
  </ol>
  
  <p><strong>Instead of that</strong>, if you debug or check the console you will see that browser repeats the section:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>if (node.nextElementSibling != null) {
      node = node.nextElementSibling;
      mostrarNodosV2 (node);
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Where node = meta, and <strong>so we get two 'TITLE' printed on console</strong>. Then it goes as it should have gone, and we get the 'body' node. The same problem happens with the 'LI' element.</p>
  
  <p>So, I do not want another solution, I just did it, I just want to know why I go back to that 'if', because I don't get it. </p>
  
  <p>If you debug it on developer tools it would be easier to understand.</p>