HTML Template: Reusable Document Fragments
Store inert markup
A normal template holds a reusable fragment rather than displaying its children. Access its DocumentFragment through content. A fragment is a lightweight container of nodes, not a rendered wrapper. The ordinary document query cannot find the paragraph inside this fragment.
<template id="card"> <p>Reusable note</p></template><p id="result"></p><script> const t = document.querySelector("#card"); document.querySelector("#result").textContent = t.content.querySelector("p").textContent;</script>Only the result paragraph is rendered.
Clone before inserting
Use cloneNode(true) to copy the fragment and descendants. Appending a fragment moves its children into the destination. Appending the original content would empty the template. document.importNode(template.content, true) is another choice, especially when the destination document differs or custom-element creation context matters.
<template id="note"> <li>Read chapter</li></template><ul id="list"></ul><script> const t = document.querySelector("#note"); const list = document.querySelector("#list"); list.append(t.content.cloneNode(true)); list.append(t.content.cloneNode(true));</script>Two list items appear; the template still has its original item.
Populate a fresh fragment
For each item, clone or import the template, then change the clone before appending it. textContent inserts text, not parsed markup. Avoid repeated IDs in cloned markup; use classes or local queries instead. Event listeners attached with addEventListener are not copied by cloneNode.
<template id="row"> <li class="topic"></li></template><ul id="topics"></ul><script> const template = document.querySelector("#row"); for (const name of ["HTML", "CSS"]) { const fragment = template.content.cloneNode(true); fragment.querySelector(".topic").textContent = name; document.querySelector("#topics").append(fragment); }</script>Two independently populated list items appear.
Common mistakes and practice
Practice changing one clone without modifying the source. Do not confuse an ordinary template with declarative shadow DOM, introduced later.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Template: Reusable Document Fragments — Knowledge Check
Apply the components concepts taught in this lesson.
Where are ordinary template children stored?
Which operation copies descendants?
What happens when a fragment is appended?
Which is suitable for inserting plain text?
Are listeners added with addEventListener cloned?