JAVASCRIPT
Replace an Existing DOM Element with a New Element
Master the technique of swapping an existing element in the DOM with a freshly created or retrieved element using JavaScript effectively.
function replaceElementWithNew(oldElementId, newElementType = 'p', newElementText = 'This is the new content!') {
const oldElement = document.getElementById(oldElementId);
if (!oldElement) {
console.error('Old element not found.');
return;
}
const newElement = document.createElement(newElementType);
newElement.textContent = newElementText;
newElement.style.border = '2px solid red'; // Example style for the new element
newElement.style.padding = '10px';
// Using replaceWith() method (modern and simpler)
oldElement.replaceWith(newElement);
console.log(`Element #${oldElementId} replaced with a new ${newElementType} element.`);
}
// Example Usage:
// <div id="originalDiv">This is the original content.</div>
// replaceElementWithNew('originalDiv', 'h3', 'I am a brand new heading!');
//
// <span id="mySpan">Hello Span!</span>
// replaceElementWithNew('mySpan', 'strong', 'I am strong now!');
How it works: This snippet shows how to completely replace an existing DOM element with a new one. The modern `Element.replaceWith()` method provides a straightforward way to achieve this. It removes the `oldElement` from its parent and inserts `newElement` in its place, making it a concise and readable solution for dynamic content updates. For older browsers, `parentNode.replaceChild(newElement, oldElement)` would be used.