HTML <template> Tag

The <template> tag serves as a container with HTML content that can be cloned multiple times and placed into the page with JavaScript.

The template itself is not visible.

The <template> content is only visible after it has been cloned and added to the page.



A <template> element that contains a dropdown control.

  Approval Status: 
    <option value="">-- Select Status --</option>
    <option value="pending">Pending</option>
    <option value="approved">Approved</option>
    <option value="rejected">Rejected</option>

Using <template>

A <template> is a container of HTML elements that can be cloned by JavaScript.

Once cloned, it can be placed anywhere on the page.

The main purpose of this element is to allow reuse of HTML elements with great performance.

An example where a template is helpful is adding new rows to a table (see below).

More Examples

A <template> that contains a table row with three blank input fields. Each time the 'Add Row' button is clicked a template input row is cloned and added to the table -- up to a maximum of 6 rows.

This design allows for rapid data entry of new user records.

First Name Last Name Email
<table id="user-table">
  <th>First Name</th>
  <th>Last Name</th>
   <td><input type="textbox" name="firstname" value="Anna"></td>
   <td><input type="textbox" name="lastname" value="Kroger"></td>
   <td><input type="textbox" name="emailname" value=""></td>

<button onclick="addRow()">Add Row</button>

<template id="user-row">
   <td><input type="textbox" name="firstname"></td>
   <td><input type="textbox" name="lastname"></td>
   <td><input type="textbox" name="emailname"></td>

  let counter = 0;

  let addRow = () => {

     if (++counter > 6) {
        alert("Max rows reached");

     let template = document.getElementById("user-row");
     let newRow = template.content.cloneNode(true);

     let table = document.getElementById("user-table");

Note: This example is not entirely complete. In a real-world solution the textboxes need to be assigned a unique name when added to the table.

Attributes for <template>

The <template> element has no attributes, but it does accept global attributes. Below are attributes that JavaScript may use to locate <template> elements.

Attribute Value Description
id   identifier Defines a unique identifier for the template.
class   classnames Assigns a CSS class to the template.
Use this class for JavaScript selection only.

For additional global attributes see our global attributes list.

Note: CSS class names are often used by JavaScript to quickly locate multiple elements.
A common convention is to prefix these classes with 'js-' to indicate they are not used for styling.

Browser support

Here is when <template> support started for each browser:

26.0 Mar 2013
22.0 Jun 2013
13.0 Nov 2015
15.0 Jul 2015
9.0 Sep 2015

You may also like

Last updated on Sep 30, 2023