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.

HtmlData Fetching

Code

snippet
<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