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
templateis, 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.
- Card Builder Lab
- True or False?
- The Code
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.
True or false?
Images inside a template start downloading when the page loads.
Scripts inside a template run when the page loads.
document.getElementById can find an element that sits inside a template's content.
You must clone the content each time you want a fresh copy.
Setting innerHTML to a visitor's text is a safe way to fill a cloned template.
Cloning content that contains id attributes can create duplicate ids on the page.
<ul id="cards"></ul>
<template id="card-template">
<li class="card">
<h3 data-field="name"></h3>
<p data-field="role"></p>
<a data-field="link">Profile</a>
</li>
</template>
const template = document.getElementById("card-template");
const list = document.getElementById("cards");
function httpsUrl(text) {
try {
const url = new URL(text, location.href);
return url.protocol === "https:" ? url.href : null;
} catch (e) {
return null;
}
}
function addCard(person) {
// 1. Clone: a fresh copy every time
const card = template.content.cloneNode(true);
// 2. Fill: textContent keeps visitor text as plain text
card.querySelector('[data-field="name"]').textContent = person.name;
card.querySelector('[data-field="role"]').textContent = person.role;
// 3. Check addresses before using them
const link = card.querySelector('[data-field="link"]');
const safe = httpsUrl(person.profile);
if (safe) link.href = safe;
else link.remove();
// 4. Insert
list.append(card);
}
addCard({ name: "Ada", role: "Engineer", profile: "https://example.com/ada" });
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.getElementByIdanddocument.querySelectordo 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 div | A template | |
|---|---|---|
| Content is in the page's DOM | Yes | No, it is in template.content |
| Images load | Often yes | No |
| Scripts run | Yes | No |
Its ids can clash with others | Yes | No, until cloned |
Found by querySelector | Yes | Only through template.content |
Using a Template: Four Stepsโ
- Find it. Give the
templateanid, and look it up. Theidgoes on thetemplateelement itself, not on things inside. - Clone it.
template.content.cloneNode(true)makes a fresh copy. Thetruemeans "copy everything inside". - Fill it. Find the parts you need in the clone, and set their text and attributes.
- Insert it. Add the clone to the page with
append,appendChild, orprepend.
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:(orhttp:if you must), as thehttpsUrlhelper in the code does. - Never place a visitor's text straight into
hreforsrc. Ajavascript: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 noforis needed. - Or generate a unique
idfor each clone, such as"name-" + counter, and setforto 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?โ
| Approach | Good for | Weakness |
|---|---|---|
template | Reusable chunks you write as real HTML | Needs JavaScript to use |
String concatenation with innerHTML | Almost nothing | Hard to read, and unsafe with visitor data |
document.createElement | Small, simple pieces | Verbose for bigger markup |
| A framework's templates | Large apps with lots of changing data | Extra code and tooling |
| Web components | Reusable elements with their own styles and behaviour | More 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โ
- In DevTools, open Elements. The
templateshows a#document-fragmentinside, which is its content. - In the Console, try
document.querySelector("#card-template h3"). It should benull. - Try
document.getElementById("card-template").content.querySelector("h3"). It should find the heading. - Open Network. Images inside a template should not load until cloned.
- Add the same card twice, and check that ids are unique with
document.querySelectorAll("[id]"). - Type markup as a name, and check it appears as text.
- Turn off JavaScript, and see what visitors get.
Best Practicesโ
- Write repeated markup as a
template, not as strings. - Always clone with
cloneNode(true), or useimportNode. - Fill with
textContent, neverinnerHTML, for visitor data. - Check URL schemes before setting
hreforsrc. - Find parts with
data-attributes. - Avoid
idinside templates. - Build lists in a fragment, and insert once.
- Attach event handlers in JavaScript.
- Load your script after the template, or use
defer. - 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
idclashes 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โ
innerHTMLwith visitor text is the classic XSS bug. Templates exist partly to avoid it, but only if you fill them withtextContent. 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, orsrcdocfrom 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โ
- Appending
template.contentwithout cloning. - Filling visitor data with
innerHTML. - Placing a visitor's text straight into
href. - Using
idinside a template, then cloning it many times. - Running the script before the template exists.
- Searching the page for elements that are inside
template.content. - Writing
onclickin the template markup. - Hiding a
divinstead of using a template, and loading unwanted images. - Building sentences by concatenation, which breaks translations.
- Relying on JavaScript for content that must always show.
Practice Timeโ
- In the lab, add three cards. What do the three numbers say?
- Type
<b>bold</b>as a name, and add a card. How does it appear? - Tick "Skip cloneNode", and add two cards. What happens on the second?
- Press Reset. What changed?
- Complete the True or False quiz.
- Write a template for a table row, and fill five rows from an array.
- Add a "link" field, and only set
hrefwhen the address ishttps:. - 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
templateis 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 avoidid. - 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.