Skip to main content

The template Element

You have a block of HTML that you need many times: a product card, a table row, a comment, a message. The old way is to build it from strings in JavaScript, gluing text and tags together. That is hard to read, hard to maintain, and a common source of security bugs.

The template element lets you write that block as ordinary HTML, keep it in your page, and copy it whenever you need it.

What You Will Learnโ€‹

  • What a template is, and why nothing inside it runs or loads
  • How to clone and fill a template, step by step
  • How to fill it safely, without opening a security hole
  • How to use templates for lists and table rows
  • The bugs that catch beginners, and how to avoid them
  • How templates relate to slots and web components

The Big Ideaโ€‹

A template is a blueprint, not a building. The browser reads it and remembers its structure, but it does not display it, load its images, or run its scripts. When you need a copy, you clone the blueprint and put the copy on the page.

http://127.0.0.1:5500/index.html

    What building a string by hand would have made (shown as text, never inserted):

    '<li>' + name + ' - ' + role + '</li>' => <li>Ada - Engineer</li>

    The template here is a real template element. Try typing a name with angle brackets, then add a card: it appears as plain text. Nothing is stored or sent anywhere.

    What Makes a Template Specialโ€‹

    The browser parses everything inside a template, but treats it as inert:

    • It is never displayed. The element itself has no visual box.
    • Images and other resources do not load. Nothing is fetched until you use the content.
    • Scripts do not run, and styles inside do not apply to the page.
    • Its elements are not part of the page. document.getElementById and document.querySelector do not find them.

    The content is stored in a separate document fragment, available as template.content. Open the lab and look at the two numbers: the page sees 0 elements inside the template, while template.content holds the blueprint.

    Compare this with hiding a div:

    A hidden divA template
    Content is in the page's DOMYesNo, it is in template.content
    Images loadOften yesNo
    Scripts runYesNo
    Its ids can clash with othersYesNo, until cloned
    Found by querySelectorYesOnly through template.content

    Using a Template: Four Stepsโ€‹

    1. Find it. Give the template an id, and look it up. The id goes on the template element itself, not on things inside.
    2. Clone it. template.content.cloneNode(true) makes a fresh copy. The true means "copy everything inside".
    3. Fill it. Find the parts you need in the clone, and set their text and attributes.
    4. Insert it. Add the clone to the page with append, appendChild, or prepend.

    document.importNode(template.content, true) also works, and is a good habit when your template contains custom elements, because it makes the copy part of the main document straight away. For ordinary markup, cloneNode(true) is fine.

    Find parts with data attributesโ€‹

    Inside the clone, use something stable to find each part. Attributes such as data-field="name" are a good choice. They say what each part is for, and they do not mix with styling classes or with ids. (A slot is a different thing, and belongs to the next lesson.)

    Filling It Safelyโ€‹

    This is the most important section of the lesson.

    Use textContent for text, and setAttribute or properties for attributes:

    card.querySelector('[data-field="name"]').textContent = person.name;

    textContent always treats the value as plain text, even if it contains angle brackets. Try it in the lab: type <b>hello</b> as the name and add a card. It shows exactly as typed, tags and all.

    Compare that with building a string:

    // Dangerous if name comes from a visitor
    list.innerHTML += "<li>" + person.name + "</li>";

    If name holds markup, innerHTML turns it into real elements, and that is how cross-site scripting (XSS) happens. See XSS Basics. The lab shows what the string would have contained, but never inserts it.

    For addresses, check the scheme before using one from data:

    • Accept only https: (or http: if you must), as the httpsUrl helper in the code does.
    • Never place a visitor's text straight into href or src. A javascript: address is a classic attack.

    Lists and Table Rowsโ€‹

    To show many items, loop over your data. Build everything in a fragment, then insert once:

    const fragment = document.createDocumentFragment();
    for (const row of rows) {
    const copy = rowTemplate.content.cloneNode(true);
    copy.querySelector('[data-field="item"]').textContent = row.item;
    copy.querySelector('[data-field="price"]').textContent = row.price;
    fragment.append(copy);
    }
    tbody.append(fragment);

    Adding to the page once, rather than many times, keeps the browser from re-doing its layout work again and again.

    A template can hold table rows, which a normal div cannot:

    <table>
    <tbody id="rows"></tbody>
    </table>

    <template id="row-template">
    <tr>
    <td data-field="item"></td>
    <td data-field="price"></td>
    </tr>
    </template>

    Bugs That Catch Beginnersโ€‹

    Forgetting to cloneโ€‹

    If you append template.content itself, the browser moves its children out of the template and into the page. The first time works. The second time, the template is empty, and nothing is added. In the lab, tick "Skip cloneNode" and press Add twice to see it, then press Reset.

    Duplicate ids and broken labelsโ€‹

    Every clone carries the same attributes. If a template contains id="name", each clone repeats it, and that breaks label for, anchors, and ARIA links. Avoid id inside templates:

    • Wrap inputs in their label, so no for is needed.
    • Or generate a unique id for each clone, such as "name-" + counter, and set for to match.

    The script runs too earlyโ€‹

    If your script runs before the browser has read the template, getElementById returns null. Put the script at the end of the page, or use defer, as in Script Loading.

    Inline event handlersโ€‹

    Handlers written in the markup, such as onclick="...", are blocked by a strict Content Security Policy. Attach handlers in JavaScript after cloning. See Content Security Policy.

    Nothing shows if scripts failโ€‹

    A template only produces something when JavaScript runs. If the content matters, provide a version that works without scripts, such as server-rendered HTML, and let the template handle later additions.

    Template or Something Else?โ€‹

    ApproachGood forWeakness
    templateReusable chunks you write as real HTMLNeeds JavaScript to use
    String concatenation with innerHTMLAlmost nothingHard to read, and unsafe with visitor data
    document.createElementSmall, simple piecesVerbose for bigger markup
    A framework's templatesLarge apps with lots of changing dataExtra code and tooling
    Web componentsReusable elements with their own styles and behaviourMore to learn

    A Peek Ahead: Declarative Shadow DOMโ€‹

    A template with a shadowrootmode attribute does something special: when the HTML is read, it builds a shadow root on its parent element instead of staying a blueprint.

    <user-card>
    <template shadowrootmode="open">
    <style>p { color: teal; }</style>
    <p><slot></slot></p>
    </template>
    Ada
    </user-card>

    This lets a component ship with its structure and styles directly in HTML, with no JavaScript. It works when the browser's HTML parser reads the page, and support is newer, so check MDN. You will meet slots in the next lesson, and the whole picture in Web Components in HTML.

    Checking Your Setupโ€‹

    1. In DevTools, open Elements. The template shows a #document-fragment inside, which is its content.
    2. In the Console, try document.querySelector("#card-template h3"). It should be null.
    3. Try document.getElementById("card-template").content.querySelector("h3"). It should find the heading.
    4. Open Network. Images inside a template should not load until cloned.
    5. Add the same card twice, and check that ids are unique with document.querySelectorAll("[id]").
    6. Type markup as a name, and check it appears as text.
    7. Turn off JavaScript, and see what visitors get.

    Best Practicesโ€‹

    1. Write repeated markup as a template, not as strings.
    2. Always clone with cloneNode(true), or use importNode.
    3. Fill with textContent, never innerHTML, for visitor data.
    4. Check URL schemes before setting href or src.
    5. Find parts with data- attributes.
    6. Avoid id inside templates.
    7. Build lists in a fragment, and insert once.
    8. Attach event handlers in JavaScript.
    9. Load your script after the template, or use defer.
    10. Provide content that works without JavaScript when it matters.

    Quick Checklistโ€‹

    • The template has an id, and the markup inside is valid HTML
    • Each use starts with a clone, not the original content
    • Text is set with textContent
    • Addresses from data are checked before use
    • No id clashes after cloning
    • Event handlers are attached in script, not in the markup
    • The script runs after the template exists
    • The page still makes sense without JavaScript

    Security and Privacy Notesโ€‹

    • innerHTML with visitor text is the classic XSS bug. Templates exist partly to avoid it, but only if you fill them with textContent. See XSS Basics.
    • Template content is still in the page source. Do not put secrets or private data in a template.
    • Never trust data from the network just because it arrived as JSON. Treat names, comments, and addresses as untrusted.
    • A template is not a sanitiser. If you must show visitor-written HTML, run it through a maintained sanitising library first.
    • Do not build href, src, or srcdoc from raw text. Check the scheme, as in the example above.

    Global Audience Notesโ€‹

    • Do not build sentences by joining pieces. Word order differs by language, so "Hello, " + name + "!" breaks in many languages. Keep whole phrases, with placeholders, in your translation files.
    • Plural rules differ. "1 item" and "2 items" are not enough for languages with several plural forms. Use a library or Intl.PluralRules.
    • Dates, numbers, and currencies should be formatted with Intl, using the visitor's locale, not by hand.
    • Names vary widely. Do not assume a first name and a last name, and test with long names and right-to-left scripts.
    • Right-to-left layouts need logical properties in the CSS you apply to cloned cards.

    Common Mistakes to Avoidโ€‹

    1. Appending template.content without cloning.
    2. Filling visitor data with innerHTML.
    3. Placing a visitor's text straight into href.
    4. Using id inside a template, then cloning it many times.
    5. Running the script before the template exists.
    6. Searching the page for elements that are inside template.content.
    7. Writing onclick in the template markup.
    8. Hiding a div instead of using a template, and loading unwanted images.
    9. Building sentences by concatenation, which breaks translations.
    10. Relying on JavaScript for content that must always show.

    Practice Timeโ€‹

    1. In the lab, add three cards. What do the three numbers say?
    2. Type <b>bold</b> as a name, and add a card. How does it appear?
    3. Tick "Skip cloneNode", and add two cards. What happens on the second?
    4. Press Reset. What changed?
    5. Complete the True or False quiz.
    6. Write a template for a table row, and fill five rows from an array.
    7. Add a "link" field, and only set href when the address is https:.
    8. Bonus: add a button to each card that removes it, using an event listener you attach after cloning.

    Quick Recapโ€‹

    Click a question to check your answer.

    1. What is a template?

    An element that holds HTML you can reuse. The browser parses it but does not display it, load its images, or run its scripts. Its content is stored in template.content.

    2. How do you use one?

    Find it, clone template.content with cloneNode(true), fill the copy, and insert it into the page.

    3. Why clone every time?

    Appending template.content itself moves its children into the page, leaving the template empty. A clone leaves the blueprint unchanged.

    4. How do you fill it safely?

    Use textContent for text, and check the scheme of any address before setting href or src. Never put visitor text in innerHTML.

    5. Why avoid id inside a template?

    Each clone repeats the same id, which causes duplicates and breaks labels and ARIA links.

    6. What does shadowrootmode on a template do?

    When the HTML is parsed, it builds a shadow root on the parent element, so a component can ship its structure and styles in HTML.

    Key Takeawaysโ€‹

    • A template is an inert blueprint: not shown, not loaded, not run.
    • Clone, fill, insert. Clone every time.
    • Fill with textContent, and check addresses.
    • Use data- attributes to find parts, and avoid id.
    • Build lists in a fragment, and insert once.
    • Keep scripts outside, load them after, and attach events in code.
    • Templates are the base for slots and web components.

    Next up: slot, where you will learn how a component can leave named places for a page author's own content.