CKTIS / HTML
template — an HTML fragment template
The `template` element holds an inert HTML fragment that a script can copy and insert into the document. Its contents are available through `content`, not as ordinary children of the element.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
<template id="item-template"><li></li></template>The template element declares an HTML fragment for later use. An ordinary template does not display its contents; they remain inert, so scripts inside do not execute while stored there. Both opening and closing tags are required.
The content property of HTMLTemplateElement exposes a DocumentFragment. Elements written between the tags belong to that fragment, not to the ordinary children of template. Find them with template.content.querySelector(...); adding children directly to template violates its content model.
Use template.content.cloneNode(true) to copy the structure deeply. Populate the copy and insert it into the document. Inserting a fragment moves its children, leaving the fragment itself empty. Inserting the original content instead of a copy would empty the template.
Declarative Shadow DOM is a separate use: shadowrootmode can cause the parser to create a shadow root instead of an ordinary template. The example below does not use that attribute.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Template example</title>
</head>
<body>
<template id="item-template"><li></li></template>
<ul id="items"></ul>
<script>
const template = document.getElementById('item-template');
const items = document.getElementById('items');
for (const name of ['Ada', 'Lin']) {
const fragment = template.content.cloneNode(true);
fragment.querySelector('li').textContent = name;
items.appendChild(fragment);
}
</script>
</body>
</html>Result
• Ada • Lin
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.