Description
The HTML element <template>
is used to define a generic container that can hold some HTML content, which can be cloned and used at multiple places.
The content of the <template>
element is hidden upon page loads, but it can be rendered after page load using JavaScript.
It is very useful to define an HTML code that can be cloned and used over and over again across multiple places.
The below table summarizes its usage.
Usage Details | |
Placement | The element <template> represents nothing. |
Contents | It can contain Block elements, Inline elements, and text. |
Tags | Both opening and closing tags are required. |
Versions | HTML 5 |
Syntax
Here is the basic syntax of the <template>
element.
<template>...</template>
Examples
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example - HTML Element template</title>
</head>
<body>
<p><button onclick="showProducts();">Show Products</button></p>
<table id="productsTable">
<thead>
<tr>
<th>Product</th>
<th>Sales</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 = students[i];
// Append the new row into table body
tbody.appendChild(clone);
}
}
} else {
alert("Your browser does not support template element!");
}
</script>
</body>
</html>
Attributes
The following table shows the list of supported and unsupported attributes for the <template>
element.
Attribute Type | Details |
Element-Specific Attributes | The tag <template> doesn't have any element-specific attributes. |
Global Attributes | Like all other HTML tags, the tag <template> supports the HTML Global Attributes. |
Event Attributes | The tag <template> also supports the HTML Event Attributes. |
Browser Compatibility
The tag <template>
is supported in all modern browsers.
- Google Chrome 26+
- Internet Explorer or Edge 13+
- Firefox 22+
- Apple Safari 8+
- Opera 15+