SN81
SN81

Reputation: 335

HTML Template displaying an extra template item when added via Javascript

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.

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.

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.

<script>
    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 < titles.length; i++) {
            node = document.importNode(template.content, true);
            label.innerHTML = titles[i];
            document.body.appendChild(node);
        }
    }
</script>	
<html>
    <body onload="addGalleryItem()">
        <template id="galleryTemplate">
            <div class="galleryItem">
                <img class="galleryImage" src="img.png" alt="Unknown-1" width="275" height="183">
                <div class="caption">
                    <label></label>
                </div>
            </div>
        </template>
    </body>
</html>	

Upvotes: 0

Views: 118

Answers (2)

David Bray
David Bray

Reputation: 586

is it as simple as :

<!DOCTYPE html>

but I also think you are querying your label in the wrong place:

for (var i = 0; i < titles.length; i++) {
    node = document.importNode(template.content, true);

    label = node.querySelector(".caption");     // should query here ?

    label.innerHTML = titles[i];
    document.body.appendChild(node);
}

Upvotes: 0

ecstatic
ecstatic

Reputation: 114

I think, the only thing wrong with your code is you are assigning innerhtml to the 'label' variable after 'node' variable, so the right code is

for (var i = 0; i < titles.length; i++) {
        label.innerHTML = titles[i];
        node = document.importNode(template.content, true);
        document.body.appendChild(node);
    }

template is not rendering, your loop is running 5 times as it has 5 items.

Upvotes: 1

Related Questions