title: Reimplementing getElementsByClassName using Recursion - Javascript
body: <p>I'm currently working on learning recursion and am trying to reimplement the <code>getElementsByClassName</code> function by walking the DOM using recursion. I finally feel like I've grasped the concepts but I'm having issues when I push the matching elements into a results array. Heres my code:</p>
  
  <pre><code>var getElementsByClassName = function(className){
    var results = [];
    var domWalker = function(node) {
      for (var i=0; i&lt;node.children.length; i++) {
          if (node.children[i].classList.contains(className)) {
              console.log(node.children[i])
              results.push(node.children[i])
          }
  
          if (node.children[i].children.length &gt; 0) {
              domWalker(node.children[i])
          }
  
      }
      return results;
    };
    domWalker(document.body);
    console.log(results)
  };
  </code></pre>
  
  <p>Basically, I need the results array to hold the matching elements it finds in HTML format like so:</p>
  
  <p><code>[&lt;div class="title"&gt;&lt;/div&gt;, &lt;button class="click"&gt;&lt;/button&gt;]</code></p>
  
  <p>... yet when I push these elements into my results array they change to the: <code>[div.title, button.click]</code> format.</p>
  
  <p>I added the <code>console.log</code> statement above the call to <code>results.push</code> to see if the results appear in the proper format before they are pushed to the array which they do. The results being pushed to the array are the results I'm looking for, they just appear in the wrong format.</p>
  
  <p>Why is push causing the format of my results to change and how can I get around this issue?</p>