The template Element
The <template> element holds HTML that is not rendered on load. Clone it with JavaScript to create dynamic content efficiently.
The <template> element holds HTML that is not rendered on load. Clone it with JavaScript to create dynamic content efficiently.
<template id="card-template">
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text"></p>
</div>
</div>
</template>
<div id="container"></div>
<script>
const tpl = document.getElementById("card-template");
const data = [{ title: "Card 1", text: "Content 1" }];
data.forEach(item => {
const clone = tpl.content.cloneNode(true);
clone.querySelector(".card-title").textContent = item.title;
clone.querySelector(".card-text").textContent = item.text;
document.getElementById("container").appendChild(clone);
});
</script>
template content is inert — scripts inside do not run and images do not load until cloned.