<template> Tag in HTML | Invisible Content for Reuse

The <template> tag in HTML is used to store HTML content that is not rendered on the page. Instead, this content is held in a reusable format, which can be accessed and dynamically inserted into the DOM using JavaScript. The template content remains hidden until explicitly referenced, making it useful for creating reusable UI components.

Key Points on <template> Tag:

Syntax of <template> Tag:

Syntax Example

<template>
            <!-- Content to be reused -->
        </template>

Example of <template> Tag in HTML:

This example demonstrates how to use the <template> tag to create reusable content for a list of items.

Code Example

<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Template Tag Example</title>
        </head>
        <body>
        
            <h2>Product List</h2>
            <ul id="productList"></ul>
        
            <template id="productTemplate">
                <li>Product Name</li>
            </template>
        
            <script>
                const products = ["Product 1", "Product 2", "Product 3"];
                const list = document.getElementById("productList");
                const template = document.getElementById("productTemplate");
        
                products.forEach((product) => {
                    const clone = template.content.cloneNode(true);
                    clone.querySelector("li").textContent = product;
                    list.appendChild(clone);
                });
            </script>
        
        </body>
        </html>

Output

Product List

  • Product 1
  • Product 2
  • Product 3

Attributes of <template> Tag:

Advantages of Using <template> Tag:

The <template> tag is ideal for dynamically generating HTML content with JavaScript, offering a flexible and reusable approach to create consistent, data-driven elements in web applications.