Cloning Templates with cloneNode
Stamp out template content efficiently with cloneNode(true).
Deep vs Shallow Clone
The cloneNode method accepts a boolean argument:
const template = document.getElementById('card-tmpl');
// Deep clone (true): copies all descendants
const deep = template.content.cloneNode(true);
// Shallow clone (false): only the root node, no children
const shallow = template.content.cloneNode(false);
// shallow has no children — use deep for templatesMultiple Stamps from One Template
Templates can be cloned any number of times:
const tmpl = document.getElementById('item-tmpl');
const container = document.getElementById('list');
['Alpha', 'Beta', 'Gamma'].forEach((name, i) => {
const clone = tmpl.content.cloneNode(true);
clone.querySelector('.item-name').textContent = name;
clone.querySelector('.item-num').textContent = i + 1;
container.appendChild(clone);
});
// 3 separate clones — modifying one doesn't affect othersAll lessons in this course
- The template Element Inert Content
- Cloning Templates with cloneNode
- Using template with JavaScript Rendering
- Templates vs innerHTML Security