5 min read
ā¢Question 33 of 49mediumWhat is the Template Element?
Reusable HTML templates.
What You'll Learn
- What templates are
- How to use them
- Benefits over innerHTML
The Template Element
The <template> element holds HTML that isn't rendered when the page loads. JavaScript clones and inserts it as needed.
Why Use Templates?
- Content is parsed but not rendered
- Images don't load until cloned
- Scripts don't run until inserted
- Safer than innerHTML strings
Example
index.htmlHTML
<!-- Define template (not rendered) -->
<template id="card-template">
<div class="card">
<h3 class="title"></h3>
<p class="description"></p>
</div>
</template>
<div id="container"></div>Using the Template
code.jsJavaScript
const template = document.getElementById('card-template');
const container = document.getElementById('container');
const data = [
{ title: 'Card 1', description: 'First card' },
{ title: 'Card 2', description: 'Second card' }
];
data.forEach(item => {
// Clone template
const clone = template.content.cloneNode(true);
// Fill in data
clone.querySelector('.title').textContent = item.title;
clone.querySelector('.description').textContent = item.description;
// Add to DOM
container.appendChild(clone);
});
</script>