Easy Tutorial
❮ Att Track Srclang Att Dir Compact ❯

HTML <template> Tag

Example

Using the <template> tag, the content within the tag does not display when the page loads. It can be displayed using JavaScript after loading:

<button onclick="showContent()">Show Hidden Content</button>

<template>
  <h2>logo</h2>
  <img decoding="async" src="https://static.tutorialpro.org/images/tutorialpro-logo.png">
</template>

<script>
function showContent() {
  var temp = document.getElementsByTagName("template")[0];
  var clon = temp.content.cloneNode(true);
  document.body.appendChild(clon);
}
</script>

Browser Support

The numbers in the table specify the first browser version that fully supports the element.

Element Chrome Edge Firefox Safari Opera
<template> 26.0 13.0 22.0 8.0 15.0

Tag Definition and Usage

The <template> tag defines some content that is hidden when the page loads, which can be rendered later using JavaScript.

If you have some HTML code that needs to be reused, you can set it as a common template using <template>.


More Examples

Example

Each array element in the example is used to populate the web page with a new div element. The HTML code for each div element is within the template element:

<template>
  <div class="myClass">I like: </div>
</template>

<script>
var myArr = ["Google", "tutorialpro", "Taobao", "Wiki", "Zhihu", "Baidu"];
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>

Example

Check if the browser supports the template tag:

if (document.createElement("template").content) {
  document.write("Your browser supports the template tag!");
} else {
  document.write("Your browser does not support the template tag!");
}

Global Attributes

The <template> tag supports HTML global attributes.

❮ Att Track Srclang Att Dir Compact ❯