Replace Child Element with JavaScript replaceChild

01/09/2022
Contents
In this article, you will learn how to replace child element with JavaScript replaceChild.
What is replaceChild()?
You can replace the child node of the specified node with a new node.
The syntax is as follows.
var el = document.getElementById("element");
replacedNode = el.replaceChild(newNode, oldNode);
The above is the processing content to replace the oldNode that el has with the newNode.
As a result of execution, the replaced node can be obtained as a return value.
Replace the child node of the specified element with replaceChild()
Create a sample that replaces h1 in the HTML below with h2.
HTML
<div id="element">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
JavaScript
//Get the element that has the node to replace
var el = document.getElementById("element");
//Get the existing node to replace
var oldNode = el.getElementsByTagName("h1")[0];
//Create a new node to replace
var newNode = document.createElement("h2");
//Generate text to have in the generated new node
var newNodeContent = document.createTextNode("New Lorem ipsum");
//Add text node to new node
newNode.appendChild(newNodeContent);
//Perform a replacement
el.replaceChild(newNode, oldNode);