Course contentsShow
← Web Development
Lesson 700 of 2,98212. The Document Object ModelFree lesson

Cloning Elements with cloneNode

Duplicate DOM nodes with cloneNode, understand deep vs shallow cloning, and handle event listeners.

Cloning Elements with cloneNode

You'll learn how to duplicate existing DOM elements and understand the difference between shallow and deep copies.

What is cloneNode?

The cloneNode() method creates an exact copy of a DOM element. Think of it like a photocopier for HTML elements—it duplicates everything about the element including its attributes, classes, and inline styles. However, you control how much gets copied.

Shallow vs Deep Cloning

cloneNode() accepts a boolean parameter that determines the depth of the copy:

const original = document.querySelector('.card');

// Shallow clone - only the element itself
const shallowCopy = original.cloneNode(false);

// Deep clone - element + all descendants
const deepCopy = original.cloneNode(true);

A shallow clone copies just the element wrapper—no children, no text nodes inside. A deep clone copies the entire subtree: all nested elements, text content, and attributes.

The Event Listener Caveat

Here's the catch: cloneNode() does not copy event listeners. If your original element has click handlers or other events attached via JavaScript, those won't transfer to the clone. You'll need to reattach them manually.

const button = document.getElementById('myButton');
const clone = button.cloneNode(true);

// Event listeners from 'button' are NOT on 'clone'
// You must add them again:
clone.addEventListener('click', handleClick);

document.body.appendChild(clone);

Practical Use

Cloning is useful for creating template-based elements (like repeating list items) or duplicating complex structures without recreating them from scratch with createElement().

Key Takeaway: Use cloneNode(true) for deep copies including descendants, cloneNode(false) for shallow copies, and remember that event listeners never clone—you must reattach them manually.