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
Chrome | Edge | Firefox | IE | Opera | Safari |
---|---|---|---|---|---|
Yes | Yes | Yes | No | Yes | Yes |
Mobile
Android Webview | Chrome Android | Firefox Android | Opera Android | iOS Safari | Samsung Internet |
---|---|---|---|---|---|
Yes | Yes | Yes | Yes | Yes | Yes |