Template element

Also known as: HTML template

On this page 7

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 stageOrdinary element childrenTemplate content
ParsingAdded to the main DOM treeAdded to a separate DocumentFragment
RenderingLaid out and paintedNot rendered at all
Resource loadingImages and media are requestedNo requests until cloned
Script executionInline scripts run on insertionScripts stay dormant
Selector matchingFound by querySelectorHidden from document queries
Ordinary markup versus template content

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.

APIReturns or doesTypical use
template.contentThe inert DocumentFragmentSource for every copy
cloneNode(true)A deep copy of the fragmentStamping out one instance
document.importNode()A copy adopted into the documentCross-document templates
attachShadow() with cloneA shadow root filled with markupBuilding a component’s internals
shadowrootmode attributeA shadow root created by the parserDeclarative Shadow DOM
Core APIs for working with templates

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.

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.

TechniqueParsed by browserInert contentMain drawback
Template elementYes, onceYesNeeds script to activate
Hidden divYesNo, resources still loadPollutes the live DOM
Script text templateNo, stored as textYesRequires parsing on every use
JavaScript string buildingNoNot applicableInjection risk if data is unescaped
Framework templatesCompiled by the frameworkDepends on frameworkAdds a runtime dependency
Comparison with alternative templating approaches

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.

SymptomCauseFix
Second render is emptyOriginal content was appendedClone the fragment before inserting
querySelector returns nullQuerying the document instead of the fragmentQuery template.content or the clone
Script inside clone does not runCloned scripts are marked as already startedCreate a new script element instead
Custom element not upgradedDefinition registered after insertionDefine elements before stamping copies
Injected HTML executesData inserted with innerHTMLUse textContent or setAttribute
Frequent template problems and fixes
  • Give each template an id so scripts can locate it reliably with getElementById.
  • 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.