Codectionary / Developer documentation / HTML

HTML template Element

The template element holds inert document fragments. Its contents are not rendered until JavaScript clones and inserts them into the document.

Syntax

<template id="item-template">...</template>

Examples

Cloning a template

A small, runnable example of this syntax.

<template id="message-template">
  <p class="message"></p>
</template>
<div id="messages"></div>
<script>
  const fragment = document.querySelector("#message-template").content.cloneNode(true);
  fragment.querySelector(".message").textContent = "Saved";
  document.querySelector("#messages").append(fragment);
</script>

Best practices

  • Use templates for repeated DOM structures and fill them with safe textContent rather than untrusted HTML.
  • Keep examples small while learning, then combine the idea with a real project.

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