HTML Element <template> - Example

The HTML element <template> is used to define a generic container that can hold some HTML content, which can be loaded dynamically using JavaScript.

The content of the <template> element is hidden upon page loads, but it can be rendered after page load using JavaScript.

Here is the example code, where we have a button to trigger a JavaScript method, that loads the content into the <template> element container.

  • The <template> is empty upon page load.
  • The <template> gets the HTML content upon clicking the button to load products.

Run this on IDE

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example - HTML Element template</title>
    <style>
        table, th, td { border: 1px solid black; }
    </style>
</head>
<body>
    <p><button onclick="showProducts();">Show Products</button></p>

    <table id="productsTable">
        <thead>
            <tr>
                <th>Product ID</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            <!-- Products list will be inserted here using the template element dynamically -->
        </tbody>
    </table>

    <template id="productRow">
        <tr>
            <td></td>
            <td></td>
        </tr>
    </template>

    <script>
        if("content" in document.createElement("template")) {
            var products = ["Bread", "Butter", "Cheese", "Milk"];

            function showProducts() {
                // Selecting the elements
                var tbody = document.querySelector("#productsTable tbody");
                var template = document.querySelector("#productRow");

                // Remove previous data if any
                tbody.innerHTML = "";

                // Loop through item in the products array
                for(i = 0; i < products.length; i++) {
                    // Clone the new row from template
                    var clone = template.content.cloneNode(true);
                    var td = clone.querySelectorAll("td");

                    // Add data to table cell from the array
                    td[0].textContent = i + 1;
                    td[1].textContent = products[i];

                    // Append the new row into table body
                    tbody.appendChild(clone);
                }
            }
        } else {
            alert("Your browser does not support template element!");
        }
    </script>
</body>
</html>

Overall

This example helps us understand the use cases of the HTML class attribute.