Codectionary / Developer documentation / HTML

<template>

The <template> element holds HTML content that the browser parses but does not render or execute when the page loads. Its content is inert — scripts inside it will not run, and images inside it will not load — until it is cloned into the visible DOM via JavaScript. This makes it a clean way to define reusable markup fragments for dynamic UI without building HTML strings in JavaScript.

Syntax

<template id="my-template">
  <p>Reusable content</p>
</template>

Examples

Basic Template Definition

A template holding markup that stays hidden until cloned.

<template id="card-template">
  <div class="card">
    <h3></h3>
    <p></p>
  </div>
</template>

Cloning a Template with JavaScript

Using the template to generate repeated list items dynamically.

<template id="item-template">
  <li class="item"></li>
</template>
<ul id="list"></ul>

<script>
  const tpl = document.getElementById('item-template');
  const list = document.getElementById('list');
  ['HTML', 'CSS', 'JS'].forEach(text => {
    const clone = tpl.content.cloneNode(true);
    clone.querySelector('.item').textContent = text;
    list.appendChild(clone);
  });
</script>

Best practices

  • Use template for markup that will be cloned and reused multiple times via JavaScript, like list items or cards
  • Remember that content inside a template is inert — access it via the element's .content property, not by querying it directly
  • Prefer template over building HTML strings with string concatenation or innerHTML for repeated UI patterns
  • Combine with document.importNode or cloneNode(true) to insert a copy without mutating the original template

At a glance

Purpose
Structure and meaning for web content
File extension
.html · .htm
Runs in
Web browsers
Usually used with
CSS and JavaScript

Specifications & further reading

Related HTML documentation