HTML5 template tag hello world tutorial

HTML5 template tag can be used to define template in html and instantiate it when needed. The instantiated template can be inserted in any DOM element using appendChild.

template tag example using vanilla Javascript

<template id="t1">
  <div>Template instance: <span class="instance-num">0</span></div>
<div id="container"><div>Some content</div></div>
<script type="text/javascript">
window.addEventListener("load", init);
function init() {
  for(var i=0; i < 3; i++) {
    var content = document.querySelector('#t1').content;
    var span = content.querySelector('.instance-num');
    span.textContent = i;
      document.importNode(content, true));

Few points to note about template

  1. .content property can be used to get content of a template dom element.
  2. document.importNode(content, true) imports template content with depth=true to include its children.
  3. template tag is supported by Chrome and Firefox and not by IE. One can see more info at template tag support.
  4. Images etc. in template are not loaded till template is cloned/instantiated.

Specification and Browser compatibility

HTML templatesWHATWG Living StandardDOM, HTML5
Yes 26+ Yes 22+ NoYes 13+ Yes 7.1+ Yes 15+
Android ChromeAndroid FirefoxiOS SafariIE MobileOpera Mobile
Yes 47+ Yes 44+ Yes 8+ NoYes 33+
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments