JAVASCRIPT
Swap DOM Elements with `replaceWith()`
Discover how to seamlessly replace an existing DOM element with a new element using the modern `replaceWith()` method, simplifying your DOM manipulation tasks.
function replaceElement(oldElementId, newElementHtml) {
const oldElement = document.getElementById(oldElementId);
if (!oldElement) {
console.error(`Element with ID '${oldElementId}' not found.`);
return;
}
// Create a temporary container to parse the HTML string
const tempDiv = document.createElement('div');
tempDiv.innerHTML = newElementHtml;
const newElement = tempDiv.firstElementChild;
if (newElement) {
oldElement.replaceWith(newElement);
console.log(`Element with ID '${oldElementId}' replaced successfully.`);
} else {
console.error('Could not create new element from provided HTML string.');
}
}
// Example Usage:
// Assume <p id="oldPara">This is the old paragraph.</p>
// const newHtml = '<div id="newDiv" style="color: blue;">This is the new div replacing the paragraph.</div>';
// replaceElement('oldPara', newHtml);
How it works: This snippet shows how to replace an existing DOM element with a new one using the `replaceWith()` method. It takes the ID of the element to be replaced and an HTML string for the new element. The HTML string is parsed into a DOM element, and then `replaceWith()` is called on the old element, effectively swapping it out with the new one in the DOM tree. This is a cleaner and more direct approach than using `parentNode.replaceChild()`.