Template Element for Reusable HTML
Uses the template element to define reusable HTML fragments that can be cloned and inserted into the DOM without rendering until activated.
Code
<template id="card-template">
<article class="card">
<img class="card-image" src="" alt="">
<h3 class="card-title"></h3>
<p class="card-description"></p>
<a class="card-link" href="#">Read more</a>
</article>
</template>
<template id="row-template">
<tr>
<td class="cell-name"></td>
<td class="cell-email"></td>
<td class="cell-role"></td>
</tr>
</template>
<div id="card-container"></div>
<table>
<tbody id="table-body"></tbody>
</table>
<script>
const cardTemplate = document.getElementById('card-template');
const cardContainer = document.getElementById('card-container');
const items = [
{ title: 'Item 1', desc: 'First item', img: 'img1.jpg' },
{ title: 'Item 2', desc: 'Second item', img: 'img2.jpg' },
];
items.forEach(item => {
const clone = cardTemplate.content.cloneNode(true);
clone.querySelector('.card-title').textContent = item.title;
clone.querySelector('.card-description').textContent = item.desc;
clone.querySelector('.card-image').src = item.img;
clone.querySelector('.card-image').alt = item.title;
cardContainer.appendChild(clone);
});
const rowTemplate = document.getElementById('row-template');
const tableBody = document.getElementById('table-body');
const users = [
{ name: 'Alice', email: '[email protected]', role: 'Admin' },
{ name: 'Bob', email: '[email protected]', role: 'User' },
];
users.forEach(user => {
const clone = rowTemplate.content.cloneNode(true);
clone.querySelector('.cell-name').textContent = user.name;
clone.querySelector('.cell-email').textContent = user.email;
clone.querySelector('.cell-role').textContent = user.role;
tableBody.appendChild(clone);
});
</script>The <template> element holds HTML that’s not rendered until cloned. content.cloneNode(true) creates a deep copy for insertion. This is more efficient than string concatenation and avoids XSS risks. Templates are ideal for repeating UI elements (cards, table rows, list items). They’re inert until activated, so no scripts run or images load until cloned.
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Markdown Live PreviewRender Markdown to HTML in real time with a live preview pane. Supports headings, lists, code blocks, links, emphasis, and blockquotes for documentation drafting.
Report a problem with this exampleOpens a pre-filled issue on GitHub.