The template element is the HTML element <template> that stores a fragment of inert markup which the browser parses but neither renders nor executes until a script clones it into the live document. Also called an HTML template, it gives web developers a native, declarative way to define reusable chunks of structure, such as table rows, cards or list items, directly in the page instead of building them string by string in JavaScript.
Within HTML, the template element sits close to Web components, Shadow DOM and Custom elements: it is the standard container from which component markup is stamped out. Its defining property is that its children live in a separate DocumentFragment, so they are invisible to selectors, do not load resources and do not affect layout.
How the template element keeps markup inert
The template element keeps markup inert by parsing its children into a separate content fragment rather than into the main DOM tree. When the parser meets <template>, it creates an associated document that has no browsing context, and every child node is appended to the element’s content property, which is a DocumentFragment.
Because that associated document is not rendered, the fragment’s nodes behave as if they were dormant. Images are not fetched, scripts do not run, styles do not apply and media elements do not autoplay. A call such as document.querySelector('.card') also ignores nodes inside a template, since they are not descendants of the main document.
The following table shows how ordinary markup and template content differ at each stage of page processing.
| Processing stage | Ordinary element children | Template content |
|---|---|---|
| Parsing | Added to the main DOM tree | Added to a separate DocumentFragment |
| Rendering | Laid out and painted | Not rendered at all |
| Resource loading | Images and media are requested | No requests until cloned |
| Script execution | Inline scripts run on insertion | Scripts stay dormant |
| Selector matching | Found by querySelector | Hidden from document queries |
The parser also gives <template> a permissive content model. It may appear in the head, in the body, inside a table or inside a select element, and it may hold content that would otherwise be invalid at that position, such as a lone <tr>. This flexibility is the main reason the element replaced older tricks like hidden <div> blocks and <script type="text/template"> strings.
Cloning and activating template content
Template content becomes active only when a script clones the fragment and inserts the copy into the document. The canonical pattern is template.content.cloneNode(true), where the argument true requests a deep clone of all descendants; the clone is then filled with data and appended to a target container.
An alternative is document.importNode(template.content, true), which clones the nodes and adopts them into the current document in one step. In practice both approaches produce the same result for same-document templates, and the clone remains a fragment that empties itself on insertion, moving its children to the destination.
The table lists the main APIs involved in working with templates and the purpose of each.
| API | Returns or does | Typical use |
|---|---|---|
| template.content | The inert DocumentFragment | Source for every copy |
| cloneNode(true) | A deep copy of the fragment | Stamping out one instance |
| document.importNode() | A copy adopted into the document | Cross-document templates |
| attachShadow() with clone | A shadow root filled with markup | Building a component’s internals |
| shadowrootmode attribute | A shadow root created by the parser | Declarative Shadow DOM |
A common error is to append template.content itself instead of a clone. That moves the original nodes out of the template, so the second attempt to render finds an empty fragment. Cloning first preserves the template as a reusable blueprint.
Template element and related techniques
The template element differs from other ways of defining reusable markup mainly in safety, performance and parser support. String templates require the developer to escape data correctly, while cloned DOM nodes accept data through properties like textContent, which prevents accidental script injection.
The comparison below places the template element next to the techniques it commonly replaces or complements.
| Technique | Parsed by browser | Inert content | Main drawback |
|---|---|---|---|
| Template element | Yes, once | Yes | Needs script to activate |
| Hidden div | Yes | No, resources still load | Pollutes the live DOM |
| Script text template | No, stored as text | Yes | Requires parsing on every use |
| JavaScript string building | No | Not applicable | Injection risk if data is unescaped |
| Framework templates | Compiled by the framework | Depends on framework | Adds a runtime dependency |
The element is also distinct from the slot element. A slot marks where light DOM children are projected inside a shadow tree, whereas a template only supplies the markup that the shadow tree is built from. The two are frequently used together in the same component.
Declarative Shadow DOM and server rendering
With the shadowrootmode attribute, the template element can create a shadow root directly in HTML, without any script. When the parser sees <template shadowrootmode="open"> as the first child of a host element, it attaches a shadow root to that host and moves the template’s content into it, and the template element itself disappears from the tree.
This feature, known as Declarative Shadow DOM, lets servers send fully rendered Web components that display before JavaScript loads. It improves first paint for component-based pages and allows styles encapsulated in the shadow root to apply immediately, which reduces layout shifts during hydration.
Values of the attribute are open and closed, mirroring the mode option of attachShadow(). Related attributes such as shadowrootdelegatesfocus and shadowrootclonable control focus behavior and whether the shadow root is copied when the host is cloned.
Practical guidance and common mistakes
The template element works best for repeated structures whose shape is fixed and whose data changes, such as search results, notification lists, product cards and table rows. For one-off dynamic content, creating a few elements directly is often simpler.
The table summarizes frequent problems, their causes and the usual fix.
| Symptom | Cause | Fix |
|---|---|---|
| Second render is empty | Original content was appended | Clone the fragment before inserting |
| querySelector returns null | Querying the document instead of the fragment | Query template.content or the clone |
| Script inside clone does not run | Cloned scripts are marked as already started | Create a new script element instead |
| Custom element not upgraded | Definition registered after insertion | Define elements before stamping copies |
| Injected HTML executes | Data inserted with innerHTML | Use textContent or setAttribute |
- Give each template an
idso scripts can locate it reliably withgetElementById. - Keep data out of the template itself; insert values only into the clone.
- Remember that screen readers ignore template content until it is inserted, which is the desired behavior.
- Do not rely on template content for search indexing, because crawlers may treat it as non-visible markup.
Put simply
A template element is like a rubber stamp kept in a drawer. The page holds the design of something it will need many times, such as a row in a list, but nobody sees it yet and it does nothing while it waits.
When the page needs a new row, a small script takes out the stamp, makes a copy, writes the details onto that copy and places it on the page. The stamp itself stays in the drawer, ready for the next copy. The key idea is that the pattern is stored once and reused safely as often as needed.
In practice
A developer building an order tracking page for an online store needs to show a list of up to 200 shipments that refreshes every 30 seconds. Instead of concatenating HTML strings, she places a <template id="shipment-row"> containing a table row with cells for order number, carrier, status and estimated delivery.
On each refresh, the script fetches the data as JSON, clones the template once per shipment, fills each cell with textContent and appends the rows to a fragment before inserting it into the table body in a single DOM operation. Because no values pass through innerHTML, a customer note containing angle brackets is displayed as plain text rather than interpreted as markup.
The result is faster rendering, no injection risk and markup that designers can edit directly in the HTML file without touching the JavaScript logic.