Skip to main content

HTML Tags

HTML <template> Tag

Written by Updated HTML <template> Tag exercises

The template tag holds a piece of HTML that the browser keeps but does not show. JavaScript copies it whenever it needs one, fills in the details, and adds it to the page: a card for each user, a row for each product.

Content inside <template> is not displayed, its images do not load and its scripts do not run, until you clone it. That makes it a clean, ready-made blueprint, much safer than building HTML from strings.

Syntax

html

<template id="templateID">
  <!-- HTML content to be cloned later -->
</template>

It has no attributes of its own besides the global ones. An id lets JavaScript find it.

Example

html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Template Tag Example</title>
</head>
<body>

<h2>Template Example</h2>

<template id="user-template">
  <div style="border:1px solid #ccc; padding:10px; margin:5px; border-radius:5px;">
    <h3>User: <span class="name"></span></h3>
    <p>Role: <span class="role"></span></p>
  </div>
</template>

<div id="user-container"></div>

<script>
const users = [
  { name: "Swapnil Raja", role: "Web Developer" },
  { name: "Alissha", role: "Principal" }
];

const template = document.getElementById("user-template");
const container = document.getElementById("user-container");

users.forEach(user => {
  const clone = template.content.cloneNode(true);
  clone.querySelector(".name").textContent = user.name;
  clone.querySelector(".role").textContent = user.role;
  container.appendChild(clone);
});
</script>

</body>
</html>

Two bordered cards appear, one for each user. They are not written in the HTML: the script clones the template for each person in the list, fills in the name and role, and adds the copy to the page.

The three steps

  1. Find the template: document.getElementById("user-template").
  2. Copy its content: template.content.cloneNode(true). The true copies everything inside.
  3. Fill in the copy with textContent, then add it to the page with appendChild.

Using textContent instead of innerHTML matters: text from users is shown as plain text and cannot inject HTML or scripts.

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE9+
YesYesYesYesYesNo

Not supported in Internet Explorer, where the content would show up as normal HTML.

Good to know

  • template.content is a document fragment; you clone it, you do not insert the template itself.
  • Templates are also used by Web Components, together with the slot tag.
  • With shadowrootmode="open", a template becomes a declarative shadow root, rendered straight away without JavaScript.

HTML <template> Tag exercises

Declare a template

Make a template with the id row that holds a list item with the text Item.

Result

Check your answer to see it here.