template element
A template stores an HTML fragment that is not rendered immediately. JavaScript can clone its contents and insert each copy when the application needs it.
What you will learn
- Why template contents are initially inert
- How to clone
template.content - How templates support dynamic lists and Web Components
What does template do?
Markup inside a template is parsed as a document fragment but is not displayed or made interactive until it is inserted elsewhere. This keeps the HTML structure separate from the code that decides when to create it.
Define a reusable fragment
<template id="card-template">
<article class="card">
<h2 class="card-title"></h2>
<p class="card-text"></p>
</article>
</template>
Clone and insert the contents
Get the template, clone its content, update the clone, and append it to a visible container. Pass true to cloneNode to include descendants.
Create a card safely
const template = document.querySelector('#card-template');
const container = document.querySelector('#cards');
const clone = template.content.cloneNode(true);
clone.querySelector('.card-title').textContent = 'Hello';
clone.querySelector('.card-text').textContent = 'Created from a template.';
container.append(clone);
Using textContent for user-provided text avoids treating that text as HTML. Do not build executable markup from untrusted strings.
Templates and Web Components
A template is often used inside a custom element's Shadow DOM. The component can clone its internal structure and expose controlled insertion points with slot.
A template in a custom element
const template = document.querySelector('#my-element-template');
const shadow = this.attachShadow({ mode: 'open' });
shadow.append(template.content.cloneNode(true));
Important details
- Template content does not appear until a clone is inserted into the document.
- Each clone is independent; changing one copy does not change the template or other copies.
- Give repeated interactive controls unique IDs and accessible names after cloning.
- Content that must be visible for SEO or no-JavaScript users should not exist only inside a template.