HTML <template> id Attribute

An id on a <template> tag assigns an identifier to the template.

The identifier must be unique across the page.



An id attribute on a <template> element.
Each time the button is clicked an item is added to the list.

  • Item 1

<template id="item-template">

<ul id="list">
  <li>Item 1</li>

<button onclick="add();">Add List Item</button> <br />

  let itemCount = 1;

  let add = () => {
     let template = document.getElementById("item-template");  
     let content = template.content;
     content.querySelector('li').textContent = "Item " + itemCount;
     let row = template.content.cloneNode(true);


Using id

The id attribute assigns an identifier to the <template> element.

The id allows JavaScript to easily access the <template> element.

It is also used to point to a specific id selector in a style sheet.

Tip:  id is a global attribute that can be applied to any HTML element.


<template id="identifier" />



Value Description
identifier A unique alphanumeric string. The id value must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.).

More Examples

A <template> with a unique id.
Each time the button is clicked a new row (i.e. template row) is added to the table.

ID Customer Name
  table.tb { width:300px; border-collapse: collapse; }
  .tb th, .tb td { border: solid 1px #777; padding: 5px; }
  .tb th { background: lightblue; }

<template id="mytemplate">
   <td><input type="text" name="name[]" value=""></td>

<table id="user-table" class="tb">
  <th>Customer Name</th>
   <td><input type="text" name="name[]" value="Anna Kroger"></td>

<button onclick="addRow();">Add Customer</button>

  var counter = 1;

  let addRow = () => {
     let template = document.getElementById("mytemplate");  
     let content = template.content;
     content.querySelector('span').textContent = counter;
     let row = template.content.cloneNode(true);


Code explanation

The id attribute assigns a unique identifier for the <template>.

When the button is clicked, JavaScript locates the <template> through the id.

It extracts the <template> content and add it as the last child of the table.

Browser support

Here is when id 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

 Back to <template>

Last updated on Sep 30, 2023