<template>

<template> can hold parsed HTML for later use. Its ordinary fragment is stored in .content, a DocumentFragment, rather than rendered as normal child content. Modern template also has specialized declarative-shadow and experimental uses.

Import a fragment

Activate the button to append a new item. Each import gets a distinct number and no duplicated ID.

Inspect template behaviorLink

HTML and CSS

HTML

<button type="button" id="add">Add a practice item</button>
<ul id="items"></ul>
<template id="item-template"
  ><li>Practice item <span></span></li
></template>
<script>
  let count = 0; document.querySelector("#add").addEventListener("click", () => { const fragment = document.importNode(document.querySelector("#item-template").content, true); fragment.querySelector("span").textContent = String(++count); document.querySelector("#items").append(fragment); });
</script>

CSS

Edit HTML or CSS to update the preview as you type. Copy code snippet copies the selected tab. Preview spacing and font defaults are not included.

Fragment behavior

The fragment is parsed but not displayed while it remains in template content. Access it through .content; appending to the template element itself does not update that fragment. Importing into the live document activates normal element behavior, so template is not a sanitizer for untrusted HTML.

Avoid cloning fixed IDs into the same document repeatedly. Generate unique IDs and update associated labels or use structure that needs no IDs. Use document.importNode when cloning into the current document, especially when custom elements are involved.

Other template modes

shadowrootmode="open" or closed can ask the HTML parser to create a declarative shadow root on the parent. Check support for that feature separately from ordinary template support. Experimental patching attributes are a different mechanism and should not be assumed portable.

Add two items, inspect their text, and verify that the original template remains available. For content projection into a shadow tree, see slot.

Sources and browser support

MDN: template describes the syntax and links to the specification and compatibility data. Check individual values in that table when supporting older browsers.