The template content property exposes a <template> element’s stored markup as a document fragment. Template markup remains absent from the rendered page until you explicitly clone and append that fragment. section 7.2
Use the property to:
- Select a template with document.getElementById(). section 7.2
- Clone template.content with cloneNode(true), preserving its nested markup. section 7.2
- Append the clone to the document; the resulting elements move out of the fragment. section 7.2
Rendering a template
const template = document.getElementById('button'); const clone = template.content.cloneNode(true); document.body.appendChild(clone); section 7.2
Listing 7.5. Adding a few templates to a page
<html>
<body>
<template id="button"> #1
<button>Click Me</button>
<p>
This is a template with a button
</p>
</template>
<template id="textfield">
<label>Enter</label>
<input type="text">
<p>
This is a template with a text input
</p>
</template>
<template id="list">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</template>
<script>
const template = #2
document.getElementById('button');
const clone = #3
template.content.cloneNode(true);
document.body.appendChild(clone); #4
</script>
</body>
</html>
Compare several stored templates with the script that reads one template’s content and adds its clone to the page. section 7.2
