Module 15: Modern Interactive HTML
The template Element
Store inert markup that JavaScript can clone when the page needs to create repeated content.
The template element holds HTML that is not rendered when the page loads. JavaScript can clone its content and insert it elsewhere.
<template id="course-card-template">
<article class="course-card">
<h2></h2>
<p></p>
</article>
</template>
<div id="course-list"></div>
<script>
const template = document.querySelector("#course-card-template");
const fragment = template.content.cloneNode(true);
fragment.querySelector("h2").textContent = "HTML";
fragment.querySelector("p").textContent = "Structure web pages with meaning.";
document.querySelector("#course-list").append(fragment);
</script>
The template content is inert until cloned. It is useful when a page needs to create repeated DOM structures from data.
Use textContent for plain text from data. Avoid inserting untrusted strings through innerHTML, because interpreting those strings as markup can create cross-site scripting vulnerabilities.
A template is not a data-binding system and it does not automatically fetch data. JavaScript remains responsible for selecting the template, filling it, and inserting the result. For framework-based applications, the framework’s component system may be a better fit.