ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

HTML5 Tutorial• 6 min read

HTML Templates & Web Components (<template>, <slot>)

Native reusable custom elements, shadow DOM, and template cloning

Modern HTML provides the native <template> and <slot> elements to define reusable UI components without requiring external frontend frameworks.

The <template> Element

<template>: Holds client-side HTML markup that is parsed by the browser but NOT rendered on page load.

JavaScript clones the template using template.content.cloneNode(true) and appends it to the DOM dynamically.

Web Components: Combine Custom Elements (customElements.define("user-card", UserCard)), <template>, and Shadow DOM for true style encapsulation.

Cloning HTML Templates in JavaScript
<template id="cardTemplate">
  <div class="card" style="border: 1px solid #ccc; padding: 12px; margin: 8px 0;">
    <h3 class="card-title"></h3>
    <p class="card-desc"></p>
  </div>
</template>

<div id="container"></div>

<script>
  const template = document.getElementById("cardTemplate");
  const clone = template.content.cloneNode(true);
  clone.querySelector(".card-title").textContent = "Native Web Components";
  clone.querySelector(".card-desc").textContent = "Reusing markup with pure browser APIs.";
  document.getElementById("container").appendChild(clone);
</script>
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Is content enclosed inside an HTML `<template>` element visible on the page when the page first loads?