JAVASCRIPT

Clone a DOM Element and Its Children

Efficiently duplicate any DOM element, including its entire subtree of children and all attributes, using `element.cloneNode(true)` for dynamic template rendering and reuse.

// Assume an HTML structure:
// <div id="templateContainer">
//   <div id="originalItem" class="item">
//     <h3>Item Title</h3>
//     <p>Some description.</p>
//     <button>Action</button>
//   </div>
// </div>
const originalItem = document.getElementById('originalItem');
const container = document.getElementById('templateContainer') || document.body; // Use body if templateContainer not found

if (originalItem) {
    // 1. Clone the original item deeply (true for all children)
    const clonedItem = originalItem.cloneNode(true);

    // 2. Modify the cloned item (e.g., change ID, text, etc.)
    clonedItem.id = 'clonedItem_' + Date.now(); // Ensure unique ID
    clonedItem.classList.add('cloned');
    const titleElement = clonedItem.querySelector('h3');
    if (titleElement) {
        titleElement.textContent = 'Cloned Item Title';
    }
    const paragraphElement = clonedItem.querySelector('p');
    if (paragraphElement) {
        paragraphElement.textContent = 'This is a cloned description.';
    }

    // 3. Append the modified clone to the DOM
    container.appendChild(clonedItem);
    console.log('Original Item:', originalItem.outerHTML);
    console.log('Cloned Item Added:', clonedItem.outerHTML);

    // Example: Clone again and modify further
    const anotherClonedItem = originalItem.cloneNode(true);
    anotherClonedItem.id = 'anotherClonedItem_' + Date.now();
    anotherClonedItem.querySelector('h3').textContent = 'Yet Another Cloned Item';
    container.appendChild(anotherClonedItem);
} else {
    console.error("Original item not found. Please ensure an element with id 'originalItem' exists.");
}
How it works: The `cloneNode()` method creates a duplicate of the node on which it is called. When `true` is passed as an argument (deep cloning), it also duplicates all the node's descendants. This is incredibly useful for creating templates or repeating complex UI components dynamically without having to build them from scratch each time, allowing for efficient rendering and customization.

Need help integrating this into your project?

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

Hire DigitalCodeLabs