How to replace a DOM element
By Flavio Copes
Learn how to replace a DOM element with another in JavaScript using the modern replaceWith() method, or the older parentNode.replaceChild() for wide support.
To replace a DOM element with another, call the replaceWith() method on the element you want to remove, passing the new element as argument.
Say you have a DOM element, which you have a reference to (maybe retrieved using querySelector()):
const spinner = document.querySelector('.loading-spinner')
const results = document.querySelector('.search-results')
spinner.replaceWith(results)
The spinner disappears from the page, and the results element takes its exact place in the DOM.
Replacing with a brand new element
The new element doesn’t need to exist in the page already. You can create one on the fly:
const oldHeading = document.querySelector('h2.title')
const newHeading = document.createElement('h2')
newHeading.textContent = 'Updated title'
oldHeading.replaceWith(newHeading)
replaceWith() also accepts plain strings, which become text nodes:
document.querySelector('.price').replaceWith('$29')
And you can pass multiple arguments, mixing nodes and strings. All of them take the place of the single original element.
Be careful when the new element is already in the page
If the element you pass is already attached to the DOM, it gets moved, not copied. It disappears from its old position.
If you want to keep the original where it is, pass a clone instead:
spinner.replaceWith(results.cloneNode(true))
cloneNode(true) copies the element and everything inside it.
The older way: replaceChild()
replaceWith() is supported by all modern browsers. Only very old ones, like IE11 and Edge before version 17, do not support it. If you still need to support those, transpile to ES5 using Babel, or look up the parent and use the replaceChild() method, which is much older:
spinner.parentNode.replaceChild(results, spinner)
Watch the argument order here. The new element comes first, and the one to remove comes second. It’s the opposite of what you might expect, and swapping the two is a classic mistake: you’d replace the new element with the old one, if both are in the page. With replaceWith() this problem doesn’t exist, which is one more reason to prefer it.
Related posts about platform: