Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Templates and Slots

The template Element

Master the HTML template element: why its content is inert, how to clone and fill it, differences between cloneNode and importNode, and how to use it in components.

Writing markup inside JavaScript strings gets messy fast: no syntax highlighting, quote escaping, and the temptation to build HTML with string concatenation. The <template> element is the platform's answer. It holds a chunk of ordinary HTML that the browser parses but does not render. You clone it whenever you need a copy.

What makes a template special

Content inside <template> is inert:

  • It is not displayed.
  • Scripts do not run, images do not load, styles do not apply, and media does not play.
  • Elements inside are not found by document.querySelector, because the content lives in a separate DocumentFragment available as template.content, not in the page's tree.
An inert template

The page sees nothing, the template has no children of its own, and the template script ran! line never appears. All the markup sits in t.content.

Cloning the content

To use the markup, copy template.content and insert the copy. Two ways exist:

JavaScript
const copy1 = template.content.cloneNode(true);    // deep clone
const copy2 = document.importNode(template.content, true);

Both produce a DocumentFragment holding fresh nodes. The difference is the owner document. cloneNode keeps the template's inert document as owner until you insert the nodes; importNode adopts them into the current document immediately, which also upgrades custom elements inside the content right away. Beginners can use either; for templates that contain custom elements that you need to be ready before insertion, prefer importNode.

When you append a fragment, its children move into the target and the fragment ends up empty. That is why you clone again for each copy.

Stamping a template

Notice textContent is used to fill the clones. It inserts text, not HTML, so user data cannot inject markup. Avoid innerHTML with untrusted data, even when the markup came from a template.

Templates and Shadow DOM

The combination is the standard recipe for components. Define the template once (as a module constant or a <template> in the page), then clone it into each shadow root.

JavaScript
const template = document.createElement("template");
template.innerHTML = `
  <style> :host { display: block; } </style>
  <slot></slot>
`;

class MyBox extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" }).append(template.content.cloneNode(true));
  }
}

Creating the template once at module level means the HTML string is parsed once, not once per instance. Cloning a parsed fragment is faster than assigning innerHTML many times.

A shared module-level template

Both components share one parsed template. Each gets its own cloned shadow content, and the attribute fills in the author name.

Where can a template go?

A <template> may appear almost anywhere in the document, including places where ordinary elements would be invalid, such as directly inside a <table>, <tbody> or <select>. That makes it ideal for table row stamps:

HTML
<table>
  <tbody id="rows"></tbody>
</table>
<template id="row">
  <tr><td></td><td></td></tr>
</template>

Without the template wrapper, setting innerHTML with a bare <tr> string on a div would silently drop the tr tags.

Common mistakes

  • Using template.children instead of template.content.children. The template element itself has no element children.
  • Forgetting true in cloneNode(true), which produces an empty fragment because the default is a shallow clone.
  • Reusing the fragment. After append(fragment), it is empty. Clone again.
  • IDs in templates. If you clone into the main document more than once, IDs repeat. Use classes or shadow roots.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the parsed content of a template element live?

    The content is stored in a separate DocumentFragment, which is why document queries do not find it.
  2. 2. What happens to a script inside a template?

    Template content is inert. Scripts are activated when cloned nodes are inserted into a live document.
  3. 3. Why create a template once at module level?

    Parsing once and cloning many times avoids repeated innerHTML parsing.
  4. 4. Which is the safe way to put user text into a cloned template?

    textContent inserts text only, so user data cannot add elements or scripts.

Summary

  • <template> holds inert HTML in template.content, a DocumentFragment.
  • Clone with cloneNode(true) or document.importNode(content, true) for each use.
  • Fill clones with textContent, then append the fragment.
  • Create a template once and clone it into each component's shadow root.
  • Templates can sit in contexts such as <table> where ordinary markup would be invalid.

Next: Slots: Passing Content into Components