HTML <template> Element
The <template> element stores HTML content that is not displayed when the page initially loads. The stored content can be accessed and inserted into the document later, commonly with JavaScript.
Syntax
<template>
<p>Reusable content</p>
</template>
Attributes
The <template> element supports the global HTML attributes and the following element-specific attributes:
| Attribute | Description |
|---|---|
shadowrootmode |
Creates a declarative shadow root on the template's parent element. Its values are open and closed. |
shadowrootclonable |
Specifies that the declarative shadow root can be cloned when its host element is cloned. |
shadowrootdelegatesfocus |
Specifies that focus behavior is delegated into the declarative shadow root. |
shadowrootserializable |
Specifies that the declarative shadow root can be included when the element's HTML is serialized. |
Example
This example stores a simple card inside a <template>. The template itself is not displayed; selecting the button uses JavaScript to copy the stored content and add it to the page.
Usage Notes
Content inside a <template> is parsed by the browser but is not rendered as part of the visible page. Images are not displayed, media does not play, and scripts inside ordinary template contents do not run while the content remains in the template.
JavaScript can access the template's content property, which contains a document fragment. The content can then be cloned and inserted into the document whenever it is needed.
The <template> element is also used for declarative shadow DOM when the shadowrootmode attribute is present. This is different from using a template simply as reusable inactive content.
Accessibility
Content stored inside an ordinary <template> is not part of the rendered page and is not available to users until it is inserted into the document. When template content is added to the page, use the same semantic HTML, labeling, focus management, and other accessibility practices that would apply to content written directly in the document.
Browser Support
Baseline: Widely available indicates a feature has been supported by core browsers for at least 30 months. At this stage, the feature is considered stable and safe for most websites to use without needing to worry about compatibility issues or fallbacks, as it is supported by the vast majority of users' devices and browser versions.
For detailed browser compatibility information, see Can I Use: HTML <template> Element .
Related Elements
The <template> element is commonly used with the <script> element when JavaScript is used to clone and insert its stored content.
Specifications
The <template> element is defined in the WHATWG HTML Living Standard .
