<template> elementThe <template> element can hold a reusable fragment of HTML. In an ordinary template, the browser parses the markup but keeps it separate from the displayed document: its images are not loaded and its scripts do not run while they remain in the template contents.
The content property supplies those contents as a DocumentFragment, a container for a group of nodes. They are not ordinary child nodes of the template element. A script can use content.cloneNode(true) to copy the fragment, including its descendants, and insert the copy into the document.
Cloning alone does not display anything. In the example below, the script appends the clone to a <ul>, making one <li> visible. The original fragment remains available for further copies. Appending the original content instead would move its nodes out of the template.
A template also has a declarative shadow DOM use. With shadowrootmode="open" or shadowrootmode="closed", the HTML parser can create a shadow root on a suitable parent and place the template contents there without JavaScript. A shadow root holds a component’s internal document structure. Open mode permits access through the parent’s shadowRoot property; closed mode does not expose it through that property.
Related attributes configure that shadow root: shadowrootdelegatesfocus delegates focus, shadowrootclonable permits cloning, and shadowrootserializable permits inclusion by serialization APIs that request serializable shadow roots. These settings concern declarative shadow roots rather than the ordinary reusable fragment in the example.
The ordinary template has no visible representation of its own. The visual column shows the list item inserted by the accompanying script.
Attributes: shadowrootmode, shadowrootdelegatesfocus, shadowrootclonable, shadowrootserializable, GLOBALS.
Typical layout: <template id="item-template"><li>First item</li></template> <ul id="template-list"></ul> <script> const item = document.getElementById("item-template"); document.getElementById("template-list").append(item.content.cloneNode(true)); </script>
Visual representation: