<template> element

2022-10-25

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