When several UI instances share the same structure, a <template> keeps that markup in HTML instead of rebuilding it with DOM calls or reparsing an HTML string. Its contents are parsed into an inert DocumentFragment: they do not render or affect layout until copied into the live DOM. Templates work independently of web components, but are useful for custom elements that need repeated light-DOM or shadow-DOM markup. section 8.1 section 8.9
To render a template:
- Declare a <template> with an id, then find it with a DOM query and access its .content. section 8.1.1
- Make a deep copy with template.content.cloneNode(true) or document.importNode(template.content, true). Do not append .content itself: appending a DocumentFragment moves out its children, leaving it empty. section 8.1.2
- Fill the copy through DOM queries, textContent, and attributes; then append it to the page or a component’s shadow root. Each copy has its own nodes, so changing one instance does not update another. section 8.1.1 section 8.9
Repeated product rows
A table can keep one <template> containing a <tr> with empty code and name cells. For each product, import its content, set the cells’ textContent, and append the copy to <tbody>. The same pattern fills cart-item templates from an array or supplies a product-card custom element with markup and styles. section 8.1.1 section 8.3
const tbody = document.querySelector("#product tbody"); #1
const tpl = document.querySelector("#rowTemplate"); #2
function addProduct(code, name) {
const clone = document.importNode(tpl.content, true); #3
const cells = clone.querySelectorAll("td"); #4
cells[0].textContent = code; #4
cells[1].textContent = name; #4
tbody.appendChild(clone); #4
}
addProduct("1235646565", "Vanilla Web Book");
addProduct("0384928528", "Web Components Book");
addProduct("9182310003", "Modern JavaScript Book");
The row-rendering code shows the complete clone, fill, and append sequence. section 8.1.1
Treat each copy as a new DOM tree: listeners attached with addEventListener to the template’s nodes are not copied, so attach them to rendered nodes instead. For dynamic text, prefer textContent over inserting unsanitized HTML. A stylesheet linked inside a template may not load until insertion, causing a flash of unstyled content; an inline <style>, an adopted stylesheet, preloading, or a loading state can address that trade-off. Do not use <template> merely to hide content from assistive technology. A <template> with shadowrootmode is a separate declarative-shadow-DOM use case. section 8.1.2 section 8.2.3 section 8.1.3 section 8.1


