Skip to main content

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.

Interactive Example:

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.

Understand SC 1.3.1: Info and Relationships

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);

Best Practices

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.