0Pricing
HTML Academy · Lesson

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 templates

Multiple 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 others

All lessons in this course

  1. The template Element Inert Content
  2. Cloning Templates with cloneNode
  3. Using template with JavaScript Rendering
  4. Templates vs innerHTML Security
← Back to HTML Academy