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>
</template>
<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.querySelector('#container').appendChild(
document.importNode(content, true));
}
}
</script>
Few points to note about template
.content
property can be used to get content of a template dom element.
- document.importNode(content, true) imports template content with depth=true to include its children.
- template tag is supported by Chrome and Firefox and not by IE. One can see more info at template tag support.
-
Images etc. in template are not loaded till template is cloned/instantiated.
Specification and Browser compatibility
Specification | Status | Categories |
---|
HTML templates | WHATWG Living Standard | DOM, HTML5 |
DesktopChrome | Firefox | IE | Edge | Safari | Opera |
---|
Yes 26+ | Yes 22+ | No | Yes 13+ | Yes 7.1+ | Yes 15+ |
MobileAndroid Chrome | Android Firefox | iOS Safari | IE Mobile | Opera Mobile |
---|
Yes 47+ | Yes 44+ | Yes 8+ | No | Yes 33+ |