title: HTML Template displaying an extra template item when added via Javascript
body: <p>I have an HTML template that I populate using Javascript when the on-load event is called and for some reason, the base template itself displays despite not being part of the array I loop through and I can't figure out why. From my understanding templates only show when appended to the document body, but the base template shows in addition to the appended templates (minus the last one since the base template hogs the first spot) and I can verify this by changing data in the base template. </p>
  
  <p>I cannot use a jQuery solution as this is going to be read into an iOS web view through a function that only accepts pure Javascript.</p>
  
  <p>My code is as follows, if anyone can explain why the initial template is showing itself I would greatly appreciate it. I've scoured for a solution and haven't found anything and think maybe I'm misunderstanding how the templating works. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>&lt;script&gt;
      var titles = ["Item1", "Item2", "Item3", "Item4", "Item5"];
  
      function addGalleryItem() {
          var template = document.querySelector("#galleryTemplate");
          var label = template.content.querySelector(".caption");
          var node;  
  
          for (var i = 0; i &lt; titles.length; i++) {
              node = document.importNode(template.content, true);
              label.innerHTML = titles[i];
              document.body.appendChild(node);
          }
      }
  &lt;/script&gt; </code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt;
      &lt;body onload="addGalleryItem()"&gt;
          &lt;template id="galleryTemplate"&gt;
              &lt;div class="galleryItem"&gt;
                  &lt;img class="galleryImage" src="img.png" alt="Unknown-1" width="275" height="183"&gt;
                  &lt;div class="caption"&gt;
                      &lt;label&gt;&lt;/label&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          &lt;/template&gt;
      &lt;/body&gt;
  &lt;/html&gt; </code></pre>
  </div>
  </div>
  </p>