What is replaceWith() method
The replaceWith() method is used to replace an element\node from the DOM (Document Object Model) with another element\node. Now, you may as well think why do we need a separate method to a task that can easily be done using the traditional JavaScript approach. Well, to put it in simple words, the replaceWith() methods allow the users to replace elements by directly referencing the child nodes. Previously, we had to refer to the parent node and then refer to the child node to replace the child node.
The replaceWith() method is supported by all modern web browsers except Internet Explorer. You can get the support for Internet Explorer but then you will require a Polyfill.
Syntax
The syntax of replaceWith() method is as follows:
oldNode: The element or the node that is to be replaced
newNode: The node or element that will replace the old node
You can also append multiple nodes using the replaceWith() method like so:
Now, we know the syntax of the replaceWith() method, we know what it is supposed to do, but we still don’t know how to use it. So, let’s try using it with an example.
Example
Create an HTML File with the following lines inside the <body> tag.
<h1>LinuxHint Tutorial</h1>
<code>replaceWith() method in JavaScript</code>
<div id="demo">
<p>This is a random text to be replaced</p>
</div>
<button id="btn">Click To Replace Node</button>
</center>
Let’s go over the code snippet and explain a few things:
- We created a “center” tag and placed everything inside of it to center it on the page.
- We created a “div” with the id “demo”.
- Inside the div, we have a “p” tag with some text inside it.
- We created a button outside the div to replace the text inside the p tag on the click of this button and linked it to the function “btnClick()”.
Let’s run the HTML page and this is how it looks:
Let’s create the JavaScript part of the tutorial.
First, we create the function “btnClick()”, under the script tag or in a different script file.
// put the later commands inside here
}
To change the <p> tag or its child nodes, we first need to get its reference as soon as the button is pressed. To get the reference of the <p> tag which is inside the <div> tag, we use a query selector. Since the div has the id = “demo” we use the following command:
Now we need an element that will replace the <p> tag. So, let’s create an input element and then give it some value, like:
newInput.value = "Replaced the Old Node";
Now that we have created an element to replace the
tag with, let’s actually replace it using the replaceWith() method by using the following code snippet:
Lastly, if we want to remove the button as well from the screen. To do that use:
btn.remove();
The complete code snippet would look like this:
const pTag = document.querySelector("#demo p");
const newInput = document.createElement("input");
newInput.value = "Replaced the Old Node";
pTag.replaceWith(newInput);
const btn = document.getElementById("btn");
btn.remove();
}
Run the HTML file and you will see this result:
Now to check if the <p> tag was actually replaced we can do that by checking the source code with the developer tools.
At first, it’s like this:
After clicking the Button it becomes like this:
As you can see, the <p> tag gets entirely replaced with the <input> tag, when we press the button and now there is only the input tag inside the “#demo div”.
Appending multiple nodes
We can also use the replaceWith() method to insert multiple nodes in replacement for the old node. Separate multiple nodes with a comma “, ”.
In the current example, let’s try to add a simple text node along with the Input tag by using the command:
Note: If we only write a string, it will automatically create a text node.
Output:
Replacing only childNodes with replaceWith() method
One of the main features of replaceWith() is to replace the childNodes directly. Suppose, we don’t want to entirely remove the <p> tag from the above example. Maybe, we want to remove the content inside the <p> tag and insert a <b> bold tag with some text in the <p> tag. We can do that by referencing the childNodes of the <p> tag.
First, let’s create the bold tag <b> with:
newChildNode.textContent = "I am a bold tag and the new childNode";
Now, let’s replace the first child node of the
tag by using the array syntax like:
Run the code and the output is as follows:
Let’s examine the source code from the developer tools option of the browser to check that the <p> wasn’t entirely removed rather than the bold tag and its content was added inside the <p> tag as its child nodes.
Now, as you can clearly see, we have successfully replaced the child node of the <p> tag and added another tag <b> inside it as its child node. That’s it for the replaceWith() method.
Conclusion
The replaceWith() is a really useful method in JavaScript that can be used to replace nodes and elements with new nodes and elements. This approach is definitely better than the traditional JavaScript approach of referring to the child node by using the reference of the parent node, this means we need to get the reference of the parent node as well. We learned the syntax and working of the replaceWith() method along with examples and confirmed the replacement by looking at the source code inside the browser’s developer tools.