0Pricing
HTML Academy · Lesson

Cloning Templates with cloneNode

Stamp out template content efficiently with cloneNode(true).

Cloning Templates with cloneNode is a free HTML Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the HTML Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

DocumentFragment and Performance

Batch DOM updates using DocumentFragment for performance:

const frag = document.createDocumentFragment();
const tmpl = document.getElementById('row-tmpl');

rows.forEach(row => {
  const clone = tmpl.content.cloneNode(true);
  // fill in clone...
  frag.appendChild(clone);
});

// ONE DOM append instead of many:
document.getElementById('table-body').appendChild(frag);
// Appending to a fragment doesn't trigger layout; append once for performance

Cloning and Event Listeners

Event listeners on the original template are NOT copied:

// Template definition:
const tmpl = document.getElementById('btn-tmpl');
const origBtn = tmpl.content.querySelector('.btn');
origBtn.addEventListener('click', () => console.log('click'));

// Clone:
const clone = tmpl.content.cloneNode(true);
const cloneBtn = clone.querySelector('.btn');
// cloneBtn does NOT have the click listener!
// You must re-add listeners after cloning

Adding Listeners After Clone

Attach events after cloning:

function createCard(data) {
  const clone = document.getElementById('card-tmpl').content.cloneNode(true);

  const deleteBtn = clone.querySelector('.delete-btn');
  deleteBtn.addEventListener('click', () => deleteItem(data.id));

  clone.querySelector('.title').textContent = data.title;

  return clone;  // return the fragment
}

document.getElementById('list').appendChild(createCard(item));

Using importNode

document.importNode is an alternative to cloneNode:

const tmpl = document.getElementById('card-tmpl');

// Equivalent to tmpl.content.cloneNode(true):
const clone = document.importNode(tmpl.content, true);
// importNode adopts the node into the current document
// In the same document, this is functionally identical to cloneNode

Template Slots Preview

Web Components use named slots to inject content into templates:

<template id="card-tmpl">
  <div class="card">
    <slot name="title">Default Title</slot>
    <slot name="body">Default body text.</slot>
  </div>
</template>
<!-- slot elements become placeholders for projected content -->
<!-- Covered in full in the Shadow DOM course -->

Updating Cloned Content

Methods to fill in cloned template content:

const clone = tmpl.content.cloneNode(true);

// textContent — safe, no HTML parsing:
clone.querySelector('.name').textContent = user.name;

// innerHTML — only if content is trusted:
clone.querySelector('.bio').innerHTML = trustedHTML;

// setAttribute:
clone.querySelector('.avatar').src = user.avatar;
clone.querySelector('.profile-link').href = `/users/${user.id}`;

Comparing to document.createElement

template vs createElement for repeated items:

// createElement: verbose for complex structures
const card = document.createElement('div');
card.className = 'card';
const title = document.createElement('h2');
card.appendChild(title);
// ... many lines for nested structure

// template: define once, clone efficiently
const clone = tmpl.content.cloneNode(true);
// Complex structure defined in HTML once
// Clone is fast and the template handles nesting

Memory and Templates

Template memory behavior:

  • Templates are stored in memory as DocumentFragments
  • Clones are independent copies — GC'd when removed from DOM
  • Templates themselves persist as long as the DOM element exists
  • For dynamic templates, cache the template reference outside the function

Browser Support

template element support:

  • Supported in all modern browsers since ~2014
  • No IE support (IE is end-of-life)
  • No polyfill needed for modern projects

Quick Check

Why must event listeners be re-added after cloning a template?

Recap: cloneNode

cloneNode essentials:

  • cloneNode(true) — deep copy including all descendants
  • Event listeners are NOT copied — re-attach after cloning
  • Batch appends with DocumentFragment for performance
  • Cache template reference outside render loops
  • Use textContent for safe text insertion

Frequently asked questions

Is the “Cloning Templates with cloneNode” lesson free?

Yes — the full text of “Cloning Templates with cloneNode” is free to read here on the web, and the HTML Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the HTML Academy course, upgrade to CoddyKit PRO.

What will I learn in “Cloning Templates with cloneNode”?

Stamp out template content efficiently with cloneNode(true). You practise HTML Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start HTML Academy?

No prior experience is required. HTML Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Cloning Templates with cloneNode” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this HTML Academy lesson?

Yes. Every HTML Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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