Français

<template>

Preparing invisible HTML, ready to appear when JavaScript decides

  • HTML
  • accessibility
  • semantics

<template> — The inert template

The <template> element holds HTML that is neither displayed nor executed by the browser. Its content lives in a DocumentFragment until JavaScript clones it and inserts it into the DOM. It is the foundation of Web Components.

When to use it

You want to define a reusable HTML fragment: a table row to clone, a product card template, or the internal structure of a Web Component. The content of <template> will never be displayed until you explicitly clone it.

What you gain

Accessibility: the content of a <template> is ignored by screen readers — that is the expected behavior. Once cloned into the DOM, the cloned fragment is accessible normally.

Code example

<template id="row-template">
  <tr>
    <td class="name"></td>
    <td class="score"></td>
  </tr>
</template>
 
<script>
  const template = document.getElementById('row-template');
  const clone = template.content.cloneNode(true);
  clone.querySelector('.name').textContent = 'Alice';
  clone.querySelector('.score').textContent = '42';
  document.querySelector('tbody').appendChild(clone);
</script>

Further reading