JAVASCRIPT
Replacing an Existing DOM Element with a New One
Discover how to seamlessly swap an old DOM element with a freshly created or existing new element using JavaScript's modern `Element.replaceWith()` method for dynamic content updates.
document.addEventListener('DOMContentLoaded', () => {
const oldElement = document.getElementById('originalElement');
const replaceButton = document.getElementById('replaceBtn');
if (oldElement && replaceButton) {
replaceButton.addEventListener('click', () => {
const newElement = document.createElement('h2');
newElement.textContent = 'I am the NEW heading!';
newElement.style.color = 'blue';
newElement.style.border = '1px solid blue';
newElement.style.padding = '10px';
// Replace the old element with the new one
oldElement.replaceWith(newElement);
// Disable the button after replacement
replaceButton.disabled = true;
replaceButton.textContent = 'Element Replaced!';
});
}
});
/*
HTML structure for context:
<p id="originalElement" style="color: red; border: 1px solid red; padding: 10px;">This is the original paragraph.</p>
<button id="replaceBtn">Replace Element</button>
*/
How it works: The `Element.replaceWith()` method provides a concise way to replace an element in the DOM with one or more new nodes. Unlike `parentNode.replaceChild()`, `replaceWith()` is called directly on the element to be replaced and accepts elements or strings as arguments, making it more flexible and easier to use. This snippet illustrates creating a new `h2` element and swapping it in place of an existing `p` element, completely changing the content and tag while maintaining the flow of the document.