← Back to all snippets
JAVASCRIPT

Deep Clone a DOM Element and its Children

Discover how to create an exact, independent copy of a DOM element, including all its children, attributes, and event listeners, using the `cloneNode()` method in JavaScript.

const originalElement = document.getElementById('templateItem');

// Deep clone (true) includes all descendants, attributes, and event listeners.
const clonedElement = originalElement.cloneNode(true);

// Modify properties of the cloned element to make it unique
clonedElement.id = 'newItem_' + Date.now(); // Assign a unique ID
clonedElement.querySelector('h3').textContent = 'Cloned Item Title';

// Append the cloned element to another container or its parent
document.getElementById('container').appendChild(clonedElement);
How it works: The `cloneNode()` method creates a duplicate of the node on which it's called. Passing `true` as an argument performs a 'deep' clone, meaning all children, attributes, and even event listeners attached to the original element (and its children) are copied. It's crucial to modify properties like `id` on the cloned element to avoid duplicates and ensure unique identification within the DOM after appending it.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs