I promised to write some posts about web components and related topics many months ago, and now finally found some time to get round to it. So here it is, the first topic to cover - the HTML5 template tag.

What the template tag allows you to do is specify some HTML markup that gets parsed but doesn't get rendered until you clone it and append it to the DOM, it is essentially inert. 

<template id="artist">
  <div class="item">
    <img src="" class="photo">
    <span></span>
  </div>
</template>

You can get hold of a template as you would any other DOM element, and can then access its content property and make it a copy using either of the following methods (the true argument is specified to enable deep cloning, i.e. including child elements in the copy).

var template = document.getElementById('artist');
var copy = template.content.cloneNode(true);

or alternatively:

var copy = document.importNode(template.content, true);

Once we have this cloned copy of the template you can manipulate it and append it to the DOM where you want it to appear. You'll typically use a querySelector to get hold of an element inside of the cloned template and then set its properties using JavaScript.

var output = document.getElementById('output');
copy.querySelector('img').src = 'john.jpg';
copy.querySelector('span').innerText = 'John';
output.appendChild(copy);

Remember that whatever is defined in a template is inert until it is cloned and added to the DOM, so you can even add images or a script tag inside of it and it won't load resources or execute as it gets parsed. Below is a simple demo showing the template tag in action as we discussed above.

See the Pen vsukH by Peter Elst (@peterelst) on CodePen.

Posted
AuthorPeter
CategoriesJavaScript