← Back to all snippets
JAVASCRIPT

Replace One DOM Element with Another

Efficiently swap an existing HTML element in the DOM with a new element using JavaScript's replaceWith() method, ideal for dynamic content updates.

function replaceElement(oldElementId, newElement) {
    const oldElement = document.getElementById(oldElementId);
    if (!oldElement) {
        console.error(`Element with ID '${oldElementId}' not found.`);
        return false;
    }
    if (!(newElement instanceof Element)) {
         console.error('The new element must be a valid DOM element.');
         return false;
    }

    try {
        oldElement.replaceWith(newElement);
        return true;
    } catch (error) {
        console.error('Failed to replace element:', error);
        return false;
    }
}

// Example Usage:
// Assume there's a button in your HTML:
// <button id="myButton">Click Me</button>
const newDiv = document.createElement('div');
newDiv.textContent = 'Button replaced by a div!';
newDiv.style.backgroundColor = '#f0f0f0';
newDiv.style.padding = '10px';
newDiv.id = 'replacementDiv';

replaceElement('myButton', newDiv);

// Another example: replace the newly inserted div with a new button
const anotherButton = document.createElement('button');
anotherButton.textContent = 'New Action';
anotherButton.id = 'newActionButton';
anotherButton.onclick = () => alert('New button clicked!');
// Assume there is an element with ID 'replacementDiv' now
replaceElement('replacementDiv', anotherButton);
How it works: This snippet demonstrates how to replace an existing DOM element with a new one using the replaceWith() method. This method directly replaces the target element in its parent, simplifying UI updates where one component needs to be swapped out for another without manually handling parent references and insertBefore() or removeChild(). It takes the ID of the element to be replaced and the new DOM element as arguments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs