HTML <template> tag

Definition and Usage

<template> tag as a container to hide some HTML content from the user when the page is loaded.

<template> The content inside can be rendered with JavaScript later.

If you have some HTML code that you want to reuse but only display when needed, you can use <template> tag. If there is no <template> tag, you need to use JavaScript to create HTML code to prevent the browser from rendering the code.

Instance

Example 1

Using <template> To save some content that will be hidden when the page is loaded, and use JavaScript to display it:

<button onclick="showContent()">Show hidden content</button>
<template>
  <h2>Flower</h2>
  <img src="img_white_flower.jpg" width="214" height="204">
</template>
<script>
function showContent() {
  var temp = document.getElementsByTagName("template")[0];
  var clon = temp.content.cloneNode(true);
  document.body.appendChild(clon);
}
</script>

Try It Yourself

Example 2

Fill the web page with a new div element for each item in the array. The HTML code for each div element is in the template element:

<template>
  <div class="myClass">I like: </div>
</template>
<script>
var myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];
function showContent() {
  var temp, item, a, i;
  temp = document.getElementsByTagName("template")[0];
  item = temp.content.querySelector("div");
  for (i = 0; i < myArr.length; i++) {
    a = document.importNode(item, true);
    a.textContent += myArr[i];
    document.body.appendChild(a);
  }
}
</script>

Try It Yourself

Example 3

Check the browser's support for <template> Support:

<script>
if (document.createElement("template").content) {
  document.write("Your browser supports template!");
}
  document.write("Your browser does not support template!");
}
</script>

Try It Yourself

Global Attributes

<template> The tag also supports Global Attributes in HTML.

Browser Support

The numbers in the table indicate the first browser version to fully support this attribute.

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
26.0 13.0 22.0 8.0 15.0