JavaScript replaceWith examples
The replaceWith function replaces a element with another. This post will go through basic and advanced examples of how to use the replaceWith function.
Apr 10, 2022 | Read time 7 minutes🔔 Table of contents
Today I learnt about the replaceWith
JavaScript function. When creating dynamic interactions with JavaScript, in some scenarios you want to replace one HTML element with another.
For example, for apps like shopping carts, when the user clicks on the cart button, you may want to swap out the div
with an empty cart number
with another div
that has the cart item count.
To acheive this type of interaction we can use the JavaScript function of replaceWith
.
replaceWith() - passing in a single Node
The replaceWith
function replaces an element with another element or collection of elements (or Nodes
)
For example, lets say we have the following HTML:
<div>
<p id="replaceMe">Hello!</p> <!-- paragraph to be replaced -->
</div>
Now if we want to replace the p
paragraph, we can use the replaceWith function.
const p = document.getElementById("replaceMe"); // get the p element
const span = document.createElement("span"); // create a new span
p.replaceWith(span); // call to replace the element
This will result in the following - paragraph element p
was replaced with a span
:
<div>
<span></span> <!-- span that replaced the previous p -->
</div>
replaceWith() - passing in multiple Nodes
A more advanced usage scenario is passing in multiple Nodes - eg a list of Nodes. In the below example, we have a div
with a single
paragraph:
<div>
<p id="replaceMe">Hello!</p> <!-- paragraph to be replaced -->
</div>
In our JavaScript we create a span
and a br
element to replace the p
element above. We can pass in multiple values to replace the paragraph element
like so:
const span = document.createElement("span");
const br = document.createElement("br");
p.replaceWith(span, br); // can pass in multiple values
This results in:
<div>
<span></span>
<br>
</div>
In addition to passing multiple parameters, you can also pass in a list or even use the spread operator:
replaceWith(...Nodes)
;
As an example:
const span = document.createElement("span");
const br = document.createElement("br");
let list = [span, br]
p.replaceWith(list); // can pass in a list of DOM nodes
replaceWith() - passing in a string
Another way to call the replaceWith
function is to give it a string. According to the spec, we can pass it Node(s) and DOMString.
So if we use the above HTML as an example, if we call p.replaceWith("Hello")
- we will get the following:
<div>
Hello
</div>
Now when you call call with HTML string such as: p.replaceWith("<h1>Hello</h1>")
, the HTML will be escaped!
(the <
and >
symbols used to create HTML tags are converted into <
and >
symbols.)
<div>
<h1>Hello</h1>
</div>
This behaviour is due to the replaceWith
function considering that the input string is a Text
node instead of HTML elements.
Jquery version
Keep in mind that the native replaceWith
is different to the one that is specified in jQuery: https://api.jquery.com/replacewith/
Both functions are fairly similar, but they have minor differences. The differences are as follows:
- the jQuery
replaceWith()
function returns the original Element where you call the method from - jQuery
replaceWith
takes in a string and can convert them to DOM elements. As for the native replaceWith function, it takes the string as-is
Browser support with polyfills
Browser support for this replaceWith
functions is pretty good - most modern browsers will support this without issue. The one exception is older versions of IE (Internet Explorer)
that is older than version 11.
If you must support users using internet explorer 11, we can use their native replaceNode
function. This function has the same signature:
IHTMLDOMNode retVal = oldObject.replaceNode(newReplacement);
The difference with the replaceNode
function is that it only accepts single DOM elements. We cannot pass it strings or multiple values or lists like the modern replaceWith
function.
The function returns the IE representation of a DOM element which is IHTMLDOMNode
.
Tips and use cases
When using the
replaceWith
function, keep in mind that when we replace the element, the associated event handlers will also go with it.For example, if you are replacing a button with another Node element, then the first button that is replaced and along with all its event handlers will be gone.
One scenario where I found this function useful is when we combine it with
cloneNode
. In some cases, a element may have too many event listeners attached to it and we want a clean reset.
cloneNode
(https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode) clones an element but does not copy the event handlers.
const box = document.getElementById('box');
// 👇️ add 2 event listeners
box.addEventListener('click', function handleClick() {
console.log('box clicked first');
});
box.addEventListener('click', function handleClick() {
console.log('box clicked second');
});
// ✅ Remove event listeners from Element
box.replaceWith(box.cloneNode(true));
In the above example, the box element got 2 event listeners on click
. Now when we use the cloneNode
, we cloned the element only.
The attached event listeners will be gone after the replaceWith
call.
(Note: the cloneNode(true) - the true
parameter just tells the function to clone deep along the subtrees aswell)
Final thoughts
In this post we learnt a few ways to use the replaceWith function to replace DOM nodes. The function can take in a single Node, multiple Node parameters, a list of nodes and DOMString.
When passing DOMString, the function will take the string as-is. If the string contains <
or >
symbols, they will be escaped to the <
and >
values.
Browser support for this function is pretty good across modern browsers (chrome, firefox, safari, etc). The only exception is with internet explorer versions below version 11.
In this case you have to use replaceNode
function instead.
When combined with other functions such as cloneNode
- we can have interesting use cases. For example, replacing the element will remove the event handlers
associated with it we can reset elements by clone it and adding it back in.