<template> element
The <template>
element is useful if you want to dynamically create markup based on a predefined “template” (great naming right there).
Example markup:
<template>
<div>
<h3>any markup, really</h3>
<!-- watch out for FOUT if you also load relevant styles -->
<link rel="stylesheet" href="url-to-stylesheet.css">
</div>
</template>
<div class="my-target"></div>
Example script
// grab the template
const template = document.getElementById('my-template');
// clone the templates content
const clonedTemplate = template.content.firstElementChild.cloneNode(true);
// optionally modify the cloned tree here
// append to `.my-target`
document.targetSelector('.my-target').appendChild(clonedTemplate);
👉 The first child of (the
) is not strictly necessary, but as the MDN article on states, certain events like click do not work if the templates content is cloned directly (template.content.cloneNode(true)) instead of firstElementChild.cloneNode(true).