JAVASCRIPT

Clone an Existing DOM Element and Modify Its Content

Learn to duplicate an existing HTML element, including its children and attributes, using `cloneNode()`, then modify the clone before appending it to the DOM.

const originalCard = document.getElementById('templateCard');
const container = document.getElementById('cardContainer');

if (originalCard && container) {
    // Clone the original card deeply (true includes children)
    const clonedCard = originalCard.cloneNode(true);
    
    // Modify content/attributes of the cloned card
    const title = clonedCard.querySelector('.card-title');
    const body = clonedCard.querySelector('.card-body');

    if (title) title.textContent = 'Cloned Card Title';
    if (body) body.textContent = 'This is content for the new cloned card.';
    
    clonedCard.id = 'clonedCard_' + Date.now(); // Ensure unique ID
    clonedCard.style.backgroundColor = '#e0ffe0'; // Example style change

    // Append the modified clone to the container
    container.appendChild(clonedCard);
}

// HTML Structure (example):
// <div id="cardContainer"></div>
// <div id="templateCard" style="border: 1px solid #ccc; padding: 10px; margin-bottom: 10px;">
//   <h3 class="card-title">Original Card</h3>
//   <p class="card-body">This is the original card content.</p>
// </div>
How it works: This snippet demonstrates how to duplicate an existing HTML element using `cloneNode(true)`. The `true` argument ensures a deep clone, including all child nodes. After cloning, the snippet modifies the title and body text of the cloned element, assigns a unique ID, and applies a new background style. Finally, the modified clone is appended to a designated container, making it a powerful technique for creating repeated UI components from a template.

Need help integrating this into your project?

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

Hire DigitalCodeLabs