How to replace a DOM element

By

Learn how to replace a DOM element with another in JavaScript using replaceWith(), or the older parentNode.replaceChild() API.

~~~

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.

For changing text on an existing node without replacing it, see how to change a DOM node value.

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()

Every current browser supports replaceWith(). Before it existed, you had to look up the parent and call its replaceChild() method:

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.

You’ll still find replaceChild() in older codebases. It keeps working, so there is no need to rewrite that code.

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about platform: