HTML · The document layer

What is the template element used for?

MediumtemplatedomjavascriptUpdated Oct 2026
Quiz this track

Short answer

The template element holds inert HTML that is not rendered or loaded until JavaScript clones its content. It is useful for repeated markup, such as rows, cards or dialog contents.

Content inside a template lives in a document fragment, not in the live document. Images do not load, scripts do not run, and the markup is not displayed until you clone it and insert it.

html
<template id="row-template">
  <tr>
    <td class="name"></td>
    <td class="role"></td>
  </tr>
</template>

<script>
  const template = document.querySelector("#row-template");
  const row = template.content.cloneNode(true);
  row.querySelector(".name").textContent = "Asha";
  row.querySelector(".role").textContent = "Engineer";
  document.querySelector("tbody").append(row);
</script>

Why it is useful

  • Repeated markup is defined once in HTML instead of built with string concatenation
  • The content is inert, so hidden media and scripts do not load or run
  • The content property returns a DocumentFragment you can clone
  • cloneNode(true) copies the subtree, including nested elements
  • It works well with Web Components and progressive enhancement

The template itself never appears in the accessibility tree. Only the inserted clones are part of the document, so make sure the cloned markup is complete and accessible.

Do not put a template inside a table and expect the browser to keep invalid table children. The parser may relocate elements. Place the template outside the table and insert valid rows.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Does content inside a template load images?
  2. 2What is the difference between template and a hidden div?
  3. 3Why does cloneNode need the true argument?
  4. 4Where should a template for table rows be placed?

Say it in the interview

The template element holds markup that is inert until I clone it. Its content lives in a document fragment, so images do not load and scripts do not run while it sits in the page. I use it for repeated rows, cards or dialog markup, then clone the content and fill in the data. Only the inserted clones are rendered and exposed to assistive technology, so the cloned markup still needs to be complete and accessible.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live HTML mock interview and get scored feedback on depth, clarity and confidence.