Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Custom Elements

The Template Element

Learn how the template element holds inert HTML, how to clone it with importNode and cloneNode, and how Lit's html tag builds on the same idea for fast rendering.

When a component creates the same markup many times, writing innerHTML = "..." over and over is slow and error-prone. The HTML <template> element solves this. Its content is parsed once by the browser, stays inert (images do not load, scripts do not run, nothing is rendered), and can then be copied as often as you like.

Templates are one of the four web component standards. They are also the idea behind Lit's html tag, so understanding them explains why Lit renders so quickly.

An inert block of HTML

Anything inside <template> is stored in a separate DocumentFragment, reachable through the content property. It does not appear on the page.

Clone a template

cloneNode(true) makes a deep copy, and append moves the fragment's children into the page. Using textContent for the values is important: it treats data as text, so a title such as <b>hi</b> is shown literally and cannot inject markup.

cloneNode versus importNode

Both copy a node, but they differ in which document owns the copy:

JavaScript
tpl.content.cloneNode(true);          // stays in the template's inert document
document.importNode(tpl.content, true); // adopted by the main document immediately

When you insert the clone into the page, it is adopted automatically, so both work in practice. The difference matters for custom elements inside the template: with importNode, they are upgraded as soon as the copy is created, which is what you usually want. Lit uses document.importNode for this reason.

Why templates are fast

The browser's HTML parser is far faster than building elements one createElement at a time. A template parses the markup once. Each clone only copies already-built nodes. For a list with hundreds of rows, that is a big saving over setting innerHTML for each row, because every innerHTML assignment reparses a string and rebuilds nodes.

Templates in a custom element

A common pattern is to create the template once, at module level, and reuse it in every instance:

A component that clones a template

The template, created once, holds both styles and structure. Each instance clones it into its own shadow root (see Shadow DOM Basics). The styles inside the template stay scoped to that shadow root.

Note the weak spot: after cloning, you have to find each spot with querySelector and fill it by hand. In a bigger component that is a lot of bookkeeping, and when the data changes you must remember to update every spot again. This exact problem is what Lit solves with ${...} bindings.

Where template content cannot go

A <template> can appear almost anywhere, including inside <table>, <select> or <head>, where ordinary elements would be invalid. Its content is parsed in a special mode that allows that. That makes it the right tool for <tr> and <option> templates.

HTML
<table>
  <tbody id="rows"></tbody>
</table>
<template id="row-tpl">
  <tr><td class="name"></td><td class="score"></td></tr>
</template>

If you tried to build the same rows from a string set with innerHTML on a <div>, the parser would drop the <tr> and <td> tags.

From template to Lit

The html tag from Lit is a smarter version of the pattern you just used:

JavaScript
const view = (name) => html`<span class="name">${name}</span>`;

On the first render, Lit turns the template literal's static strings into a real <template>, remembers where each ${...} hole is, and clones it. On later renders it skips parsing and the cloning, and updates only the holes whose values changed. You get the speed of templates without the manual querySelector code. The next chapters explain this in Lit Templates and Bindings.

Template, step by step

Write HTML inside template
Parse once Inert, no load, no run

Nothing renders yet

1 / 2

Common mistakes

  • Reading template.children. Use template.content.children: the content is in the fragment.
  • Appending template.content itself without cloning. That moves the nodes out, so the template is empty for the second use.
  • Using innerHTML with user data to fill the template. Set textContent, or use attributes safely.
  • Putting <script> inside a template. Keep behavior in the component class and attach event listeners there.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to images and scripts inside a template element?

    Template content is inert: nothing loads or runs until you clone it into the document.
  2. 2. Where do you find the HTML inside a template?

    The parsed markup lives in the content property, a DocumentFragment.
  3. 3. Why does appending template.content directly (without cloneNode) break the second use?

    Appending a fragment moves its children. Clone first with cloneNode(true) to keep the template intact.
  4. 4. Which is the safest way to put a user-supplied name into a cloned template?

    textContent treats the value as plain text, so markup in the data is never parsed.

Summary

  • <template> stores inert HTML; its parsed content is in template.content.
  • Clone with cloneNode(true) or document.importNode(content, true), then fill and insert.
  • Parsing once and cloning is much faster than repeated innerHTML.
  • Templates can hold table rows and options, where normal markup would be dropped.
  • Lit's html tag applies the same idea and removes the manual filling.

Next: Upgrading and Defining Elements