JAVASCRIPT
Cloning an Existing DOM Element
Master how to create exact duplicates of existing HTML elements in the DOM, including their content and children, using the `cloneNode()` method.
function cloneElement(elementId, deepClone = true) {
const originalElement = document.getElementById(elementId);
if (originalElement) {
const clonedElement = originalElement.cloneNode(deepClone);
// Modify ID to avoid duplicates if appending to the same document
clonedElement.id = `${elementId}-clone-${Date.now()}`;
return clonedElement;
}
console.warn(`Element with ID '${elementId}' not found.`);
return null;
}
// Example Usage:
// <div id="templateDiv"><span>Hello</span> World!</div>
// const newDiv = cloneElement('templateDiv');
// if (newDiv) {
// document.body.appendChild(newDiv);
// }
How it works: This function shows how to duplicate an existing DOM element. `cloneElement` takes an element's ID and an optional `deepClone` boolean (defaulting to `true`) to specify whether to clone its children and their content. It returns a new, independent node. A new unique ID is assigned to the cloned element to prevent ID conflicts if it's appended to the same document, making it suitable for creating templates or repeated UI components.