JAVASCRIPT
Deep Clone a DOM Element with `cloneNode()`
Learn to create an exact duplicate of a DOM element, including its content and children, using `cloneNode(true)` for template-based rendering.
function deepCloneElement(originalElementId, newId = '') {
const originalElement = document.getElementById(originalElementId);
if (!originalElement) {
console.error(`Original element with ID '${originalElementId}' not found.`);
return null;
}
// 'true' means a deep clone (includes all descendants)
const clonedElement = originalElement.cloneNode(true);
// Optionally update the ID to avoid duplicates if appending to the DOM
if (newId) {
clonedElement.id = newId;
// You might also want to update IDs of children if they exist and need unique IDs
// For example: clonedElement.querySelectorAll('[id]').forEach(el => el.id = el.id + '_cloned');
} else {
// Remove ID if not providing a new one, as IDs must be unique
clonedElement.removeAttribute('id');
}
console.log(`Element with ID '${originalElementId}' deeply cloned.`);
return clonedElement;
}
// Example Usage:
// Assume <div id="templateCard"><h2>Title</h2><p>Description</p></div>
// const clonedCard = deepCloneElement('templateCard', 'clonedCard1');
// if (clonedCard) {
// document.body.appendChild(clonedCard);
// }
// const anotherClonedCard = deepCloneElement('templateCard'); // No new ID, ID will be removed
// if (anotherClonedCard) {
// document.body.appendChild(anotherClonedCard);
// }
How it works: This snippet demonstrates how to create a deep clone of an existing DOM element using the `cloneNode()` method. When `true` is passed as an argument, `cloneNode()` duplicates the element along with all its descendants (children, grandchildren, etc.). This is extremely useful for situations where you have a template element and need to create multiple instances of it, saving the overhead of programmatically building each element from scratch. It also includes logic to manage duplicate `id` attributes for proper DOM integration.