HTML / HTML Tags

HTML <Template> Tag

Dec 12, 2022
1 min read
HTML template Tag

Definition

A <template> tag is used to declare a fragment of HTML that can be cloned and inserted into the web page using JavaScript.

Example

<!doctype html>
<html lang="en">
 <head>
  <title>Homework</title>
 <body>
  <template id="template"><p>Smile!</p></template>
  <script>
   let num = 5;
   const fragment = document.getElementById('template').content.cloneNode(true);
   while (num-- > 1) {
     fragment.firstChild.before(fragment.firstChild.cloneNode(true));
     fragment.firstChild.textContent += fragment.lastChild.textContent;
   }
   document.body.appendChild(fragment);
  </script>
</html>

Usage

  • Both the opening and closing tags are required.
  • A <template> element is permitted in any element that accepts metadata content, phrasing content, script-supporting elements, as well as a child of a <colgroup> element that has no span attributes.

Attributes

The <template> element only supports the Global Attributes.

Specification

Browser Support

Desktop

ChromeEdgeFirefoxIEOperaSafari
YesYesYesNoYesYes

Mobile

Android WebviewChrome AndroidFirefox AndroidOpera AndroidiOS SafariSamsung Internet
YesYesYesYesYesYes