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

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

Related pages