completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

The template element

Learn the HTML template element: why its content is inert, when to copy it with cloneNode or importNode, and how to fill a shadow root from one template.

By the end, you can
  • 01
    Read a template's contentFind the markup in template.content, a fragment kept in a separate document that has no window.
  • 02
    Explain why it stays asleepSay why scripts, images, styles, and custom elements inside a template wait until a copy joins the page.
  • 03
    Copy it the right wayChoose cloneNode(true) or document.importNode(), and build every shadow root from one template made once.

What is the HTML template element?

Leaf and Kettle's menu page now shows twelve tea cards, the ones Ravi finished in lesson 6.3. Each time a card is made, its constructor gives the browser the same string of HTML. So the browser reads that string twelve times, and builds the same small tree twelve times.

Asha has seen a tag called <template> in other people's code. "Could it hold the card's HTML just once?" she asks. "And where does that HTML go, if the page doesn't show it?"

The HTML template element, <template>, holds a piece of HTML that the browser reads but doesn't show or run. Your JavaScript copies its content with cloneNode(true) and adds the copy to the page, as many times as it needs.

Here is a small template. Press the button in the result a few times:

A template and a button that stamps copiesPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li>Green tea</li></template> <ul id="menu"></ul><button>Stamp a copy</button> <script>  const template = document.querySelector("#tea-row");  const menu = document.querySelector("#menu");  document.querySelector("button").addEventListener("click", () => {    menu.append(template.content.cloneNode(true));  });</script>
ResultLoading…
  • Lines 1 to 3 are the template. It holds one list item, Green tea. The result doesn't show it.
  • Line 5 is an empty list. Line 6 is a button.
  • Lines 9 and 10 find the template and the list.
  • Line 11 listens for clicks on the button. Each click runs line 12.
  • Line 12 does the work. template.content is the HTML inside the template. cloneNode(true) makes a fresh copy of it, with everything inside. append() adds the copy to the list.

At first, the result shows only the button. Each click adds one more Green tea. The template itself never changes, and it never shows.

A window called template holds a card that reads <li>Green tea</li>, with the note not shown on the page. An arrow labelled cloneNode(true) leads to a window called page, which holds three cards, each reading Green tea.template<li>Green tea</li>not shown on the pagecloneNode(true)pageGreen teaGreen teaGreen tea
The template holds one <li>, and the page never shows it. Each click on Stamp a copy runs cloneNode(true) and adds one more Green tea to the list. Three clicks, three copies.
Real-life analogyA template is the shop's loyalty stamp

Leaf and Kettle gives every customer a loyalty card. The shop owns one rubber stamp with a teapot on it. The stamp never goes into anyone's wallet. Each time someone buys a tea, Ravi presses it onto their card, and a fresh teapot appears.

In real life: The rubber stamp
In JavaScript: The <template> element
In real life: The teapot shape carved on the stamp
In JavaScript: template.content, the HTML inside
In real life: Pressing the stamp onto a card
In JavaScript: template.content.cloneNode(true)
In real life: Each printed teapot
In JavaScript: A copy added to the page with append()
The main idea

A <template> holds HTML that the browser reads once and keeps asleep. Its markup lives in template.content, away from the page. Nothing in it shows, runs, or loads. To use it, copy the content with cloneNode(true) and add the copy to the page.

Lesson 1.1 stamped a template like this twice, in a loop. This lesson answers Asha's questions in order: where the content lives, why it stays asleep, which way to copy it, and how a component uses one.

Where does a template's content live?

The browser reads everything between <template> and </template>. But it doesn't make those tags children of the template. Look:

The template's children, and its contentPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li>Green tea</li></template> <script>  const template = document.querySelector("#tea-row");  console.log(template.childNodes.length);  console.log(template.content.children.length);  console.log(template.content.querySelector("li").textContent);</script>
ResultLoading…
  • Lines 1 to 3 are a template with one <li>.
  • Line 7 asks how many child nodes the template has. It prints 0.
  • Line 8 asks how many elements its content holds. It prints 1.
  • Line 9 finds the <li> inside content and prints its text, Green tea.

So the <li> isn't a child of the template. It lives in template.content. That's the one place to read a template's markup. For a template written in HTML, MDN notes that childNodes is always empty.

A fragment in a separate document

What kind of thing is content? Ask it:

What content is, and which document owns itPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li>Green tea</li></template> <script>  const content = document.querySelector("#tea-row").content;  console.log(content.nodeName);  console.log(content.ownerDocument === document);  console.log(content.ownerDocument.defaultView);</script>
ResultLoading…
  • Line 6 keeps the template's content in a variable.
  • Line 7 prints #document-fragment. A DocumentFragment is a light holder for nodes, with no parent of its own. When you add one to the page, its children move in, and the empty holder stays behind. Creating & changing elements, on the JavaScript path, covers fragments.
  • Line 8 prints false. Every node belongs to one document, and its ownerDocument says which. This fragment's document isn't the page.
  • Line 9 prints null. defaultView is the window that shows a document. This document has none.

The HTML Standard explains why. Each page gets one extra, hidden document. It holds the content of every template on that page. Its browsing context is null: no tab, no frame, and no window ever shows it. The standard calls it the template contents owner document.

Real-life analogyTemplate content waits in the shop's storeroom

Behind Leaf and Kettle's counter is a storeroom. Spare cups wait on its shelves. Customers can't see them, and nothing is sold from there. When the shop floor needs a cup, Ravi carries one out.

In real life: The shop floor
In JavaScript: The page's document
In real life: The storeroom behind the counter
In JavaScript: The template contents owner document, which has no window
In real life: A spare cup waiting on a storeroom shelf
In JavaScript: The markup in template.content
In real life: Carrying a cup out to the shop floor
In JavaScript: Adding a copy to the page
A window called page holds a card that reads <template>, with the note the page's document. An arrow labelled content leads to a window called template doc. It holds a card that reads #document-fragment and, under it, a card that reads <li>Green tea</li>. The note under it says it has no window.page<template>the page's documentcontenttemplate doc#document-fragment<li>Green tea</li>it has no window
The <template> element sits in the page's document. Its content is a #document-fragment that belongs to a second document, made for templates. That document has no window, so nothing in it shows or runs.

Lesson 3.5 sent a badge into this same storeroom and watched adoptedCallback() run. Why it matters: anything that needs a window, like running a script or loading a picture, can't happen in there.

The content empties when you append it

A fragment gives its children away when you add it somewhere. So if you append template.content itself, the template is empty afterwards:

Appending the content itself, twicePop out in the code editor (opens in a new tab)HTML
<template id="tea-row"><li>Green tea</li></template><ul id="menu"></ul> <script>  const template = document.querySelector("#tea-row");  const menu = document.querySelector("#menu");  menu.append(template.content);  menu.append(template.content);  console.log(menu.children.length);  console.log(template.content.children.length);</script>
ResultLoading…
  • Line 7 adds template.content to the list. Its <li> moves into the list.
  • Line 8 does it again. But the fragment is empty now, so nothing moves.
  • Line 9 prints 1: the list has one item. Line 10 prints 0: the template has nothing left.

That's why every example in this lesson copies first. A copy leaves the template full for next time. Why it matters: append a copy of content, never content itself.

Templates made in JavaScript

You can also make a template in JavaScript, with document.createElement("template"). Fill it through its innerHTML. On a template, innerHTML reads and writes the content, not the children. But append() still adds children:

innerHTML fills the content, append() doesn'tPop out in the code editor (opens in a new tab)JavaScript
const good = document.createElement("template");
good.innerHTML = "<li>Green tea</li>";
console.log(good.content.children.length);
console.log(good.innerHTML);

const bad = document.createElement("template");
bad.append(document.createElement("li"));
console.log(bad.content.children.length);
console.log(bad.childNodes.length);
  • Lines 1 and 2 make a template and set its innerHTML. Line 3 prints 1: the <li> went into content.
  • Line 4 prints <li>Green tea</li>. Reading innerHTML gives back the content's markup.
  • Lines 6 and 7 make a second template and append() an <li> to it.
  • Line 8 prints 0: the content is empty. Line 9 prints 1: the <li> became a real child of the template. Nothing ever copies it from there.

MDN warns about this: a child added that way breaks the template's rules and doesn't change content. To fill a template in JavaScript, set its innerHTML, or append to template.content.

Templates in tables and lists

Most tags must sit in the right place. Put a <div> inside a <table>, and the browser moves it out of the table. Templates are allowed in more places. The HTML Standard lets one sit inside a <table>, a <ul>, or a <select>, and its content keeps table rows and list items. Switch between a template and a div:

Playground: a template or a div inside a table?
A row inside a table, held by a template or a divPop out in the code editor (opens in a new tab)HTML
<table>  <template id="row">    <tr><td>Green tea</td></tr>  </template></table> <script>  const row = document.querySelector("#row");  console.log(row.parentElement.localName);  console.log(row.innerHTML.includes("<tr>"));</script>
ResultLoading…
Try it yourself
The template stays in the table

Line 9 prints table: the template stayed where you wrote it. Line 10 prints true: its content kept the <tr>. The page shows nothing, because the row is still in the template.

Each choice changes lines 2 and 4. Line 9 prints where the holder ended up, and line 10 whether it still holds the row.

With the template, line 9 prints table and line 10 prints true. With the div, line 9 prints body, and the row escapes into the table without it. Why it matters: a template can sit right next to the rows it makes copies for.

Why doesn't template content run or load?

The storeroom has no window, so nothing in it ever wakes up. Things that would act at once on a page just wait:

  • Scripts don't run.
  • Images, stylesheets, and script files aren't loaded. Chrome doesn't even ask for them.
  • Styles don't apply to anything.
  • Audio and video don't load or play.
  • Custom elements aren't upgraded.
  • document.querySelector() can't find anything inside.

Content like this is called inert: it's there, but asleep. The playground puts the same three tags in three places. They are a style, a script, and an image. The image is drawn from a short data: address, so it needs no file. Its onload attribute prints a line when it loads.

Playground: inside a template, or not?
A style, a script, and an image, in three placesPop out in the code editor (opens in a new tab)HTML
<p>Green tea</p> <div id="extras">  <style>p { color: seagreen; }</style>  <script>console.log("The script ran");</script>  <img alt="" width="20" height="20" onload="console.log('The image loaded')"    src="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'/>"></div>
ResultLoading…
Try it yourself
Everything runs and loads

In a div, the three tags are part of the page. The style turns Green tea sea green, the script prints, and the image loads.

The same three tags each time: a style on line 4, a script on line 5, and an image on lines 6 and 7. Watch the color of Green tea and the console.
  • In a div, the tags are part of the page. Green tea turns sea green. The console prints The script ran and The image loaded.
  • In a template, nothing happens. Green tea stays black, and the console stays empty.
  • A copy added to the page wakes everything up. Line 12 adds the copy, and both lines print again.
Real-life analogyTemplate content is tea in a sealed tin

A tin of tea can sit on a shelf for months. The leaves are all there, but nothing brews. Put a spoonful in hot water, and the tea is ready in minutes. The tin stays sealed and full.

In real life: The sealed tin
In JavaScript: The template's content
In real life: The dry leaves inside
In JavaScript: Its scripts, images, styles, and custom elements
In real life: Hot water
In JavaScript: The page
In real life: Brewing one spoonful
In JavaScript: Adding a copy to the page

Chrome's network log shows the same thing. An image, a stylesheet, or a script file inside a template makes no request at all. Each request starts only when a copy joins the page. An <audio autoplay> inside a template never loads, and calling its play() fails. Its copy plays as soon as it's added, and a <video> works the same way. Why it matters: a page can keep big templates without paying for their pictures until they're used.

Custom elements and searches

A tea label inside a templatePop out in the code editor (opens in a new tab)HTML
<template id="card">  <tea-label name="Green tea" minutes="3"></tea-label></template> <script src="tea-label.js"></script><script>  console.log(customElements.get("tea-label") !== undefined);  console.log(document.querySelector("tea-label"));  const label = document.querySelector("#card").content.querySelector("tea-label");  console.log(label.matches(":defined"));</script>
ResultLoading…
  • Line 5 loads the tea label from lesson 1.1, in the tea-label.js tab. It defines tea-label.
  • Line 7 prints true: the page knows the tag.
  • Line 8 searches the page for a tea-label. It prints null. Searches from the page skip template content.
  • Line 9 searches content instead, and finds the label. Line 10 prints false: it isn't upgraded.

The template's document has no window, so it has no registry either. Elements in it stay plain. Lesson 4.1 showed that even customElements.upgrade() skips them. Why it matters: to read template markup, search template.content. To use a component inside, copy it into the page first.

Scripts in a copy

The playground's copy printed The script ran. A script copied from a template in your HTML runs when its copy joins the page. But a script that came in through innerHTML never runs, in a template or anywhere else. The HTML Standard marks it as already started, and a copy keeps that mark. Why it matters: don't count on scripts inside templates. Put your code in your component instead.

Should you use cloneNode or importNode?

There are two ways to copy a template's content. Both take true for a deep copy, with everything inside:

  • template.content.cloneNode(true) is a method of the node you copy.
  • document.importNode(template.content, true) is a method of the document that will own the copy.

Both give you a new fragment to add to the page. The difference is which document owns the copy. That decides when custom elements inside it are upgraded. Switch between them:

Playground: cloneNode or importNode?
One template row, copied two waysPop out in the code editor (opens in a new tab)HTML
<ul id="menu"></ul><template id="tea-row">  <li><tea-label name="Green tea" minutes="3"></tea-label></li></template> <script src="tea-label.js"></script><script>  const template = document.querySelector("#tea-row");  const copy = template.content.cloneNode(true);  const label = copy.querySelector("tea-label");  console.log("Owned by the page:", copy.ownerDocument === document);  console.log("Upgraded:", label.matches(":defined"));   document.querySelector("#menu").append(copy);  console.log("In the page, upgraded:", label.matches(":defined"));</script>
ResultLoading…
Try it yourself
The copy waits in the template's document

The copy belongs to the template's own document, which has no registry. So the label stays plain until line 14 adds it to the page. Then it upgrades.

Only line 9 changes. Lines 11 and 12 check the copy before it joins the page, and line 15 checks it after.
  • Line 9 makes the copy. Your choice changes it.
  • Line 11 asks whether the page's document owns the copy. Line 12 asks whether the label inside is upgraded.
  • Line 14 adds the copy to the list. Line 15 asks again.

With cloneNode(true), lines 11 and 12 print false. The copy was made in the template's own document, so it waits there as plain elements. Line 15 prints true. append() moved the copy into the page, and the label upgraded there.

With importNode(), the copy belongs to the page from the start. Its label is upgraded before line 14 even adds it. Both choices end the same way: the result shows Green tea: brew for 3 minutes.

Two rows. In the first, labelled template.content.cloneNode(true), a card content leads to a card copy: not upgraded, in the template's document, which leads through append() to a card upgraded. In the second, labelled document.importNode(template.content, true), a card content leads to a card copy: upgraded, in the page's document, which leads through append() to a card upgraded.template.content.cloneNode(true)contentcopy: not upgradedthe template's documentappend()upgradeddocument.importNode(template.content, true)contentcopy: upgradedthe page's documentappend()upgraded
Both copies end up upgraded in the page. A cloneNode() copy belongs to the template's document and stays plain until append(). An importNode() copy belongs to the page and upgrades as it's made.
Real-life analogyTwo photocopiers, one in the storeroom

Ravi needs copies of a menu card with an empty price box. He can use the copier in the storeroom and carry the copies out. Or he can use the copier at the counter. Asha fills in the prices, and she works only at the counter. So a storeroom copy stays blank until it reaches her. A counter copy gets its price right away.

In real life: The copier in the storeroom
In JavaScript: template.content.cloneNode(true)
In real life: The copier at the counter
In JavaScript: document.importNode(template.content, true)
In real life: Asha filling in prices at the counter
In JavaScript: The page's registry upgrading custom elements
In real life: Carrying the copies out
In JavaScript: append() adding the copy to the page

The HTML Standard says the same. Its own template example copies with cloneNode(), and says importNode() would do the same thing. The only difference is when the copy changes documents: when you append it, or when you copy it. MDN suggests importNode() for templates, so custom elements are built from the page's definitions as they're copied.

For the usual job, both work: copy the content, then append it straight away. Pick importNode() when your code uses a component inside the copy before adding it, such as calling one of its methods. For the details:

  • Lesson 3.6 showed when each callback runs for both kinds of copy.
  • Lesson 4.1 showed upgrade() skipping a cloneNode() copy.
  • Lesson 3.5 compared importNode() with adoptNode(), which moves the node itself.

Read each row across: what you write, who owns the result, when components inside upgrade, and what's left in the template.

Ways to use a template's content
What you writeWho owns the result?When do components inside upgrade?Is the template still full?
template.content.cloneNode(true)The template's own document, until you add it to the page.When the copy joins the page.Yes. You used a copy.
document.importNode(template.content, true)The page's document, from the start.As the copy is made.Yes. You used a copy.
list.append(template.content)The page. These are the template's own nodes, not a copy.When they join the page.No. The template is empty now.
template.content.cloneNode()The template's own document.There's nothing inside to upgrade.Yes, but the copy is empty: without true, no children come along.

Watch for the last row. Without true, both methods make a shallow copy: the fragment alone, with nothing inside.

What a copy leaves behind

cloneNode() and importNode() copy markup: tags, attributes, and text. They don't copy what a script added to a node later:

A listener and a property that stay behindPop out in the code editor (opens in a new tab)HTML
<template id="buy">  <button>Buy Green tea</button></template><div id="shelf"></div> <script>  const template = document.querySelector("#buy");  const button = template.content.querySelector("button");  button.addEventListener("click", () => console.log("Bought"));  button.price = 4;   const copy = template.content.cloneNode(true);  console.log(copy.querySelector("button").price);  document.querySelector("#shelf").append(copy);</script>
ResultLoading…
  • Line 8 finds the button inside the template's content.
  • Line 9 gives it a click listener. Line 10 gives it a property, price.
  • Line 12 copies the content. Line 13 prints undefined: the copy's button has no price.
  • Line 14 adds the copy to the page. Click Buy Green tea in the result. Nothing prints: the listener stayed on the template's button.

Why it matters: add listeners to each copy, after you clone it. MDN warns about the same thing for a listener on the fragment itself. Exercise 6 fixes a page with this bug.

How do you fill a shadow root from a template?

Back to Ravi's twelve cards. A component's shadow root is a good home for a template copy. Find or make the template once. In the constructor, clone it into the new shadow root:

A note component cloned from a template in the pagePop out in the code editor (opens in a new tab)HTML
<template id="note">  <style>    p { margin: 0; color: seagreen; }  </style>  <p>Fresh today</p></template> <tea-note></tea-note><tea-note></tea-note><p>Our teas</p> <script>  const template = document.querySelector("#note");   class TeaNote extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.append(template.content.cloneNode(true));    }  }   customElements.define("tea-note", TeaNote);</script>
ResultLoading…
  • Lines 1 to 6 are the template: a style and a paragraph.
  • Lines 8 and 9 use the new tag twice. Line 10 is a paragraph of the page.
  • Line 13 finds the template once, when the script runs.
  • Line 18 gives each note a shadow root, as in lesson 6.1.
  • Line 19 clones the template's content into it. Each note gets its own copy.

The result shows Fresh today twice, in sea green. Our teas stays black. The template's <style> went into each shadow root, so it only styles that root's paragraph. MDN's guide builds a component the same way.

A template made in the component's file

A template in the page ties the component to that page. Every page that uses <tea-note> would need the same <template id="note">. A component can make its template in its own file instead:

A note component that makes its own templatePop out in the code editor (opens in a new tab)HTML
<tea-note></tea-note><tea-note></tea-note><tea-note></tea-note> <script type="module" src="tea-note.js"></script>
ResultLoading…
  • The page, lines 1 to 3, uses three notes. Line 5 loads tea-note.js, the second tab, as a module.
  • In tea-note.js, line 1 makes a template with document.createElement("template"). Lines 2 to 6 set its innerHTML.
  • Lines 1 to 6 sit outside the class, at the top of the module. They run once, when the file first loads.
  • Line 12 runs for every note. It only clones.

A module's top-level variables stay inside its file. So template can't clash with anything on the page.

Why cloning beats parsing a string

Why not set this.shadowRoot.innerHTML in the constructor, as lesson 6.1 did? It works. But the browser then reads and parses the same string for every card. With a template, it parses once. Each card copies nodes that are already built.

Chrome's guidance for web components says it directly. Define a template once, at module level or in a static field, and clone it per instance. It calls cloning a parsed fragment "far faster than re-parsing an innerHTML string on every construction". Lit, the library in stage 8, works the same way. The first time it meets a piece of HTML, it makes a <template>. Each new place that shows that HTML gets a clone of it.

Real-life analogyA template is a cookie cutter

Asha bakes forty teapot biscuits for the shop. She could trace the teapot with a knife on every biscuit, looking at the drawing each time. Or she could bend a cookie cutter into the shape once, and press it forty times. Each press is quick, and every biscuit comes out the same.

In real life: Tracing the drawing with a knife, every time
In JavaScript: Parsing an HTML string in every constructor
In real life: Bending the cutter into shape once
In JavaScript: Making the template once, at the top of the module
In real life: Pressing the cutter into the dough
In JavaScript: template.content.cloneNode(true)
In real life: Each biscuit
In JavaScript: Each card's own shadow root
A window called module holds one card that reads template, with the note made once, cloned per card. Three arrows lead from it to three windows called tea-card. Each holds a card that reads its own copy.moduletemplatemade once, cloned per cardtea-cardits own copytea-cardits own copytea-cardits own copy
The module makes one template. Each card's constructor clones it, so each of the three cards gets its own copy in its own shadow root. The HTML is parsed once, not three times.

Templates that become shadow roots

There's one more way <template> meets shadow DOM. Write <template shadowrootmode="open"> inside an element in your HTML. The browser turns that template into the element's shadow root, with no JavaScript at all. This is called declarative shadow DOM. Server rendering, stage 9, teaches it.

MDN's template page also lists an experimental for attribute, which only Chrome supports. It patches content into the page as it loads. The templates in this lesson use neither attribute.

Building the tea card from one template

Now Ravi's card. In lesson 6.3, its constructor set this.shadowRoot.innerHTML. The kit's new version makes one template at the top of tea-kit/tea-card.js, and clones it for each card. Here is a menu with two cards:

Two kit cards, each with its own copyPop out in the code editor (opens in a new tab)HTML
<tea-card name="Green tea" price="4"></tea-card><tea-card name="Oolong" price="5"></tea-card> <script type="module">  import "./tea-kit/index.js";   const [first, second] = document.querySelectorAll("tea-card");  console.log(first.shadowRoot.getElementById("name").textContent);  console.log(second.shadowRoot.getElementById("name").textContent);  console.log(first.shadowRoot.firstElementChild === second.shadowRoot.firstElementChild);</script>
ResultLoading…
  • Lines 1 and 2 are two cards. Line 5 loads the whole kit.
  • Lines 8 and 9 read each card's heading. They print Green tea and Oolong.
  • Line 10 compares the first element in each card's shadow root. It prints false. Each card has its own copy, not a shared one.

Here is the card's new file. It's also one of the tabs above:

The kit's tea card, built from one templateJavaScript
const template = document.createElement("template");
template.innerHTML = `
  <style>
    .card { border: 2px solid seagreen; border-radius: 8px; padding: 8px 12px; }
    h3 { margin: 0; color: seagreen; }
    p { margin: 4px 0 0; }
  </style>
  <article class="card" aria-labelledby="name">
    <h3 id="name"></h3>
    <p id="price"></p>
  </article>`;

/**
 * A tea card: a tea's name and price in a box. Its own shadow root holds the box and its styles.
 *
 * @tag tea-card
 * @attr {string} name - The tea's name.
 * @attr {string} price - The tea's price.
 */
export class TeaCard extends HTMLElement {
  static observedAttributes = ["name", "price"];

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.append(template.content.cloneNode(true));
  }

  attributeChangedCallback(name, oldValue, newValue) {
    const text = newValue ?? "";
    if (name === "name") this.shadowRoot.getElementById("name").textContent = text;
    if (name === "price") this.shadowRoot.getElementById("price").textContent = `Price: ${text}`;
  }
}

customElements.define("tea-card", TeaCard);
  • Line 1 makes the template. It runs once, when the kit loads.
  • Lines 2 to 11 set its markup: the same style and article as in lesson 6.3.
  • Lines 13 to 19 are the card's JSDoc comment, which tools read. It stays right above the class it describes.
  • Line 26 takes the place of lesson 6.3's innerHTML string. It clones the template into the new shadow root. The rest of the class is unchanged.
  • Lines 29 to 33 fill in the name and the price, as before.

Every card shows the same box, heading, and price as lesson 6.3's card. Each one keeps its tea's name as its accessible name. Only the work inside the constructor changed: one copy instead of one parse.

Common mix-ups

  • "Template content is hidden markup in the page." No. It isn't in the page's tree at all. It lives in a fragment owned by another document. document.querySelector() can't find it, and nothing in it runs or loads.
  • "Custom elements inside a template are live." No. They stay plain. A copy upgrades when it joins the page, or as it's made with importNode().
  • "cloneNode and importNode are the same." No. Both make a copy, but each copy starts in a different document. A cloneNode() copy belongs to the template's document until you append it. An importNode() copy belongs to the page at once.
  • "Listeners added to template nodes come along when you clone." No. A copy gets tags, attributes, and text. Listeners and properties set by a script stay behind.
  • "You can append template.content to use it." No. Appending moves the nodes out, so it works only once, and the template is empty after that. Clone first.
  • "Templates are written in a script tag." No. Old guides used <script type="text/template"> strings or Polymer's <dom-module>. <template> replaced both.

Practice exercises

Answer first, then use the hints. Each result runs live, so you can check yourself.

Exercise 1 · Warm-upChildren or content?

What does the console print?

<template id="row"><li>Green tea</li></template> <script>  const template = document.querySelector("#row");  console.log(template.childNodes.length, template.content.childNodes.length);</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upA script in a template

    What does the console print?

    <template id="kettle">  <script>console.log("Brewing");</script></template> <script>  console.log(document.querySelector("template script"));</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeOne template for every note

      Each note parses its HTML again in its constructor. Change the script so it makes one template and clones it for every note. What does each note show?

      <tea-note></tea-note><tea-note></tea-note> <script>  // Make one template here, and clone it in the constructor.  class TeaNote extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = "<p>Fresh today</p>";    }  }   customElements.define("tea-note", TeaNote);</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFind the bug in the empty note

        The page has two notes. How many of them show Fresh today? Then fix the bug.

        <template id="note"><p>Fresh today</p></template><tea-note></tea-note><tea-note></tea-note> <script>  const template = document.querySelector("#note");   class TeaNote extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.append(template.content);    }  }   customElements.define("tea-note", TeaNote);</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeFind the bug in the empty menu

          The menu should show Green tea twice. What does line 12 print? Then fix the bug.

          <ul id="menu"></ul> <script>  const template = document.createElement("template");  const row = document.createElement("li");  row.textContent = "Green tea";  template.append(row);   const menu = document.querySelector("#menu");  menu.append(template.content.cloneNode(true));  menu.append(template.content.cloneNode(true));  console.log(menu.children.length);</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeMake every Buy button work

            Click both Buy buttons in the result. How many times does Bought print? Then make both buttons work.

            <template id="buy">  <button>Buy</button></template><div id="shelf"></div> <script>  const template = document.querySelector("#buy");  template.content.querySelector("button").addEventListener("click", () => {    console.log("Bought");  });   const shelf = document.querySelector("#shelf");  shelf.append(template.content.cloneNode(true));  shelf.append(template.content.cloneNode(true));</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, think about where the content lives: in a storeroom with no window, until a copy joins the page.

              The template element quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does line 7 of the content example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <template id="tea-row">
                  <li>Green tea</li>
                </template>
                
                <script>
                  const template = document.querySelector("#tea-row");
                  console.log(template.childNodes.length);
                  console.log(template.content.children.length);
                  console.log(template.content.querySelector("li").textContent);
                </script>

                Choose an answer to see the explanation.

              2. Question 2 of 7Where does a template's content live?

                Choose an answer to see the explanation.

              3. Question 3 of 7A template holds <img src="teapot.png">. When does the browser ask the server for teapot.png?

                Choose an answer to see the explanation.

              4. Question 4 of 7Which copy belongs to the page's document as soon as it's made?

                Choose an answer to see the explanation.

              5. Question 5 of 7In the example that appends the content itself twice, what does line 9 print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <template id="tea-row"><li>Green tea</li></template>
                <ul id="menu"></ul>
                
                <script>
                  const template = document.querySelector("#tea-row");
                  const menu = document.querySelector("#menu");
                  menu.append(template.content);
                  menu.append(template.content);
                  console.log(menu.children.length);
                  console.log(template.content.children.length);
                </script>

                Choose an answer to see the explanation.

              6. Question 6 of 7Why does the kit's tea card make its template at the top of its module?

                Choose an answer to see the explanation.

              7. Question 7 of 7Can a <template> sit inside a <table>?

                Choose an answer to see the explanation.

              Key takeaways

              • A <template> holds HTML that the browser parses but never shows. Its markup is in template.content, and its childNodes is empty.
              • content is a DocumentFragment owned by a separate document with no window. So its scripts, images, styles, media, and custom elements all stay asleep.
              • Copy the content with cloneNode(true) or document.importNode(content, true). Appending content itself empties the template.
              • A cloneNode() copy upgrades when it joins the page. An importNode() copy upgrades as it's made. Listeners and properties never come along.
              • Templates can sit in tables, lists, and selects. In JavaScript, fill one with innerHTML or template.content.append().
              • For a component, make the template once at the top of its module, and clone it into each shadow root. It's faster than parsing a string per instance.

              Remember the one-liner.
              A template is HTML the browser parses once and keeps asleep. Clone its content to stamp out a fresh, live copy wherever you need one.

              Sources

              The facts on this page come from these standards and docs:

              Coming next: Filling a template with data, the next lesson in Shadow DOM, templates, and slots. Clone a template and fill it with text, attributes, and lists, without writing HTML strings. After that, Ways to render a component compares innerHTML, cloning, and updating only what changed.

              CompleteFrontend Clear concepts. Working examples.