How to replace one element with another with vanilla JavaScript
Yesterday, we looked at how to make a copy of an element with vanilla JS. Today, we’re going to learn how to replace one element with another.
Let’s dig in.
An example
Let’s build on yesterday’s article a bit. We have a paragraph element with a greeting.
<p id="node1" class="text-blue">Hello, world!</p>
Now let’s say we want to make a copy of it, change the ID, change the class, and change the text.
// Get the original
var elem = document.querySelector('#node1');
// Make a copy
var copy = elem.cloneNode(true);
// Change all the things
copy.id = 'node2';
copy.className = 'text-purple';
copy.textContent = 'Hi, universe!';
Now let’s imagine that we want to replace the original elem
with the new copy
.
The replaceChild()
method
You call the replaceChild()
method on the target element’s parentNode
. Then, pass in the new element and the one to replace as arguments.
// Replace the original with the copy
elem.parentNode.replaceChild(copy, elem);
The replaceChild()
method works in all modern browsers, and back to IE9.
The replaceWith()
method
The replaceWith()
method uses a simpler syntax.
Call it on the original element, and pass in the copy as an argument. And that’s it.
// Replace the original with the copy
elem.replaceWith(copy);
The replaceWith()
method works in all modern browsers, but has no IE support.
Which one should you use?
If you’re using polyfill.io on your site, I would use replaceWith()
. It has a nicer syntax.
Otherwise, I would use replaceChild()
. The browser support on replaceWith()
just isn’t good enough yet without a polyfill.