The <template> Element
As defined in the HTML Living Standard, the <template> element is used to declare fragments of HTML that can be cloned and inserted into the document by script. The contents of the element are not processed by the browser until the template is used.
Click the button to instantiate a new item from a hidden template.
<template id="my-template">
<div class="card">
<h2>Dynamic Title</h2>
</div>
</template>
View HTML Living Standard: The template element
Accessibility: The Hidden Benefit
Before the <template> element, developers often used <div style="display:none"> or script tags to store HTML fragments.
WCAG Requirement: Info and Relationships
Success Criterion 1.3.1 (Level A): Information, structure, and relationships conveyed through presentation can be programmatically determined.
The <template> element is truly inert. Its content is not part of the Document Object Model (DOM) in the traditional sense and, crucially, it is not part of the Accessibility Tree. This means screen readers will not find or announce template content, preventing "ghost" elements from confusing the user before they are actually needed in the UI.
Technical Implementation
To use a template, you must use JavaScript to clone its content:
const temp = document.getElementById("my-template");
const clone = temp.content.cloneNode(true);
document.body.appendChild(clone);
- Performance: Because the content is not rendered, images inside templates are not downloaded and scripts are not executed until the template is cloned and inserted into the active DOM.
- Reusability: Templates are the foundation for modern web components and client-side rendering patterns.
Best Practices
- Naming: Use descriptive IDs for your templates so their purpose is clear in the source code.
- ARIA Live Regions: When inserting cloned content that provides important updates, ensure the container uses
aria-liveto notify screen reader users of the addition, satisfying WCAG SC 4.1.2 (Name, Role, Value). - Empty Templates: Never put content that should be indexed by search engines or read immediately by screen readers inside a
<template>.
A11y Tip: Initial State
If a template represents a complex widget (like a modal), ensure that the cloned instance has all the necessary ARIA attributes (like role="dialog") already included in the template markup.