Skip to main content

HTML <template> Tag

The HTML <template> element helps define a template of data or content to be used with JavaScript's DOM .content property. It allows developers to store content that can be used and reused multiple times within a single web page.

This content is not visible to the user when the page is first loaded, but it can be accessed and displayed using JavaScript. This makes it easy to create dynamic sections of a webpage which can be easily updated as the user interacts with the page.

<template id="button-template">
  <button class="btn btn-primary">I'm a template button!</button>
</template>

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

<script>
  var template = document.getElementById('button-template');
  var container = document.getElementById('button-container');
  const button = template.content.querySelector('button').cloneNode(true);
  container.appendChild(button);
  const button2 = template.content.querySelector('button').cloneNode(true);
  container.appendChild(button2);
</script>

In this example, the <template> element with the id "button-template" contains a button element. A script then uses this template to create 2 new button elements, which are then appended to the "button-container" element.

When the page is first loaded, the buttons in the template will not be visible to the user. However, when the script runs, it will create new buttons using the template and append them to the page, making them visible to the user.

  • One common use case for the <template> tag is to store reusable user interface elements such as buttons or form inputs. These elements can be defined once in the template and then instantiated and modified as needed throughout the page. This can help to improve the maintainability and organization of a web page, as well as reduce the amount of duplication in the code.
  • Another use case for the <template> tag is to store content that will be used to generate dynamic lists or tables. For example, a developer could create a template for a list item and then use JavaScript to dynamically populate the list with data from an external source. This can help to improve the performance and responsiveness of a web page, as it allows the content to be loaded as needed rather than all at once.
  • In addition to storing content for later use, the <template> tag can also be used to store content that is only relevant in certain conditions. For example, a developer might use a template to store content that is only relevant to users on a specific device or operating system. This content can then be conditionally displayed or hidden using JavaScript based on the user's device or operating system.