title: JS Looped appendChild producing strange behaviour
body: <p>I have this function:</p>
  
  <pre><code>//add links to called classes
  function addLinks () {
      var classElements = [];
      var idElements = [];
      var finalRender;
      var expand = document.createTextNode("+");
      var contract = document.createTextNode("-");
      var elementsList = [];
      var count = 0;
  
      //create the dom nodes
      renderPElements = document.createElement ("p");
  
          renderAElements = document.createElement ("a");
          renderAElements.setAttribute("href", "#");
          renderAElements.setAttribute("class", "expander");
          renderAElements.appendChild(expand);
          finalRender = renderPElements.appendChild(renderAElements);
  
  
      //get arrays of elements with class or id set to provided string
      for (var i = 0; i&lt; show_hide_class_selectors.length; i++) {
          classElements[i] = document.getElementsByClassName(show_hide_class_selectors[i]);
  
          //if prevents null value appearing in array and freezing script
          if (document.getElementById(show_hide_class_selectors[i])) {
          idElements[i] = document.getElementById (show_hide_class_selectors[i]);
          }
      }
  
      //loop though selected id's / classes and generate a single array of selected elements
      for (var i = 0; i&lt; idElements.length; i++) {
          elementsList[count] = idElements[i];
          count = count +1;
      }
  
      //must loop twice as variable is 2 dimensional i=class name y=elements of that class
      for (var i = 0; i&lt; classElements.length; i++) {
          for (var y = 0; y&lt; classElements[i].length; y++) {
          elementsList[count] = classElements[i][y];
          count = count +1;
          }
      }
  
      //render
      for (var i = 0; i&lt; elementsList.length; i++) {
          alert ("render");
          elementsList[i].parentNode.firstChild.appendChild(finalRender);
  
          alert (elementsList[i]);
      }
  }
  </code></pre>
  
  <p>Which is meant to take an array of classes / ids provided as a global variables and produce an array that contains all the requested elements. It is then supposed to append childnodes (links in this case) to sibling nodes by looping though the generated array using appendchild.</p>
  
  <p>However instead of resulting in a page that has a bunch of extra links on it, the final loop instead appends the child and then immediately removes it, working its way though the loop until the final element which is permitted to retain it's generated link.</p>
  
  <p>I can find no explaination for this behaviour or anyone with a similiar problem. </p>