JAVASCRIPT
Clone an Existing DOM Element with or without Children
Learn to duplicate existing HTML elements in the DOM using cloneNode() in JavaScript, creating shallow or deep copies for templating and dynamic UI generation.
function cloneElement(originalElementId, deepClone = true, targetParentId = null) {
const originalElement = document.getElementById(originalElementId);
if (!originalElement) {
console.error(`Original element with ID '${originalElementId}' not found.`);
return null;
}
const clonedElement = originalElement.cloneNode(deepClone);
if (targetParentId) {
const targetParent = document.getElementById(targetParentId);
if (targetParent) {
targetParent.appendChild(clonedElement);
} else {
console.warn(`Target parent with ID '${targetParentId}' not found. Cloned element not appended.`);
}
}
// Optional: Modify ID to prevent duplicates if appending to the same document
// and the original had an ID (IDs must be unique)
if (clonedElement.id) {
clonedElement.id = `${clonedElement.id}-cloned-${Date.now()}`;
}
return clonedElement;
}
// Example Usage:
// Assume the following HTML structure:
// <div id="template-card">
// <h3>Item Title</h3>
// <p>Description goes here.</p>
// </div>
// <div id="card-container"></div>
const card1 = cloneElement('template-card', true, 'card-container'); // Deep clone
if (card1) {
card1.querySelector('h3').textContent = 'Product A';
card1.querySelector('p').textContent = 'Detail for product A.';
}
const card2 = cloneElement('template-card', false, 'card-container'); // Shallow clone (only template-card div, no h3 or p)
if (card2) {
card2.textContent = 'This is a shallow clone.';
}
How it works: This function uses element.cloneNode(deepClone) to create a duplicate of an existing DOM element. The deepClone parameter (a boolean) determines whether the element's children should also be cloned (true for deep clone) or just the element itself (false for shallow clone). This is invaluable for creating repeated UI components based on a template without rebuilding them from scratch each time. An optional target parent ID is provided to append the cloned element directly.