Reference · Intermediate

The template element

Use template to store inert DOM fragments that scripts can clone, while keeping required content and behavior available without fragile injection.

Published
Last checked

Definition

template stores a parsed but inert document fragment. Its descendants are not rendered, scripts do not run, media does not load in the ordinary way, and form controls do not participate in the page until a script clones or moves the content into the live document.

Minimal syntax

<template id="notice-template">
  <section class="notice">
    <h2>Saved</h2>
    <p>Your changes are now stored.</p>
  </section>
</template>

JavaScript accesses the element's content, clones it, adjusts any unique values, and inserts the clone at a deliberate location.

Appropriate use

Templates suit repeated client-created UI whose structure is known at authoring time. Server rendering is usually better for primary content needed on first load. Do not hide essential navigation, legal text, or the only version of an article inside an inert fragment that requires JavaScript.

Browser and accessibility behavior

Inert descendants are absent from ordinary rendering, focus order, forms, and the accessibility tree. Once inserted, they behave like normal DOM nodes. Repeated clones must not duplicate id values, names intended to be unique, or relationships such as for and aria-describedby.

Common failures

  • Cloned controls reuse IDs and labels point to the wrong instance.
  • Untrusted strings are inserted through HTML parsing instead of safe text and attribute APIs.
  • Focus stays on a removed trigger after dynamic insertion.
  • Essential content is blank when scripts fail.

Verification checklist

Inspect the page with scripts disabled and confirm the baseline task remains available. Create several clones and validate IDs, names, labels, descriptions, focus order, and event behavior. Insert hostile-looking text as data and confirm it remains text. Test removal and reinsertion so focus and status announcements recover predictably.

Verify that every clone receives current data rather than retaining state from a previous instance. When a clone contains a form, submit several instances and confirm labels, values, errors, and server identifiers stay associated with the intended record.