title: DRY up htmlCollection to Array calls
body: <p>I have a function that is currently using the <code>.getElementBy...</code> DOM calls in JavaScript.</p>
  
  <pre><code>var $ = function (selector) {
    var elements = [];
  
    var lastSelector  = selector.substring(selector.search(/[^#.]+$/), selector.length);
  
    if(selector.includes('#') !== true || selector.includes('.') !== true) {
      elements.push(document.getElementsByTagName(lastSelector));
      elements = Array.prototype.slice.call(elements[0]);
    }
  
  return elements;
  };
  </code></pre>
  
  <p>There are a number of other if statements in the function using the code:</p>
  
  <pre><code>elements.push(document.getElementsByTagName(lastSelector));
  elements = Array.prototype.slice.call(elements[0]);
  </code></pre>
  
  <p>or</p>
  
  <pre><code>elements.push(document.getElementsByClassName(lastSelector));
  elements = Array.prototype.slice.call(elements[0]);
  </code></pre>
  
  <p>Ideally i'd like to DRY up the repeated:</p>
  
  <pre><code>elements = Array.prototype.slice.call(elements[0]);
  </code></pre>
  
  <p>but I cannot define it before the <code>if</code> statements because elements has not yet been populated. It therefore tries to run the code on an empty array and errors.</p>
  
  <p>Any suggestions?</p>