The following code shows an example of the replaceChild() method in JavaScript.
Programmingempire
Demonstrating Example of the replaceChild() Method in JavaScript
The following HTML document contains a paragraph that handles the mouseover event. When the user moves the mouse over the paragraph, function f1() executes. Further, in the function, a Button element is created using the createElement() function. After that, we retrieve the parent node of the paragraph in a variable. Then, we call the replaceChild() method that replaces the paragraph with the Button.
<html>
<head>
<title>replaceChild Method Demo</title>
<script>
function f1()
{
var x2=document.getElementById("p1");
var x3=document.createElement('BUTTON');
x3.innerText="A Button";
var xx=x2.parentNode;
xx.replaceChild(x3, x2);
}
</script>
<style>
.c1{
border: 4px solid #33ff99;
border-radius: 10px;
background-color: #5566aa;
color: #aaffff;
font-size: 20px;
text-align: center;
margin:5px;
padding: 10px;
}
.a1{
margin: 50px;
}
.c2{
background-color: #ddeeff;
color: #ff5566;
font-size: 25px;
text-align: left;
margin:40px;
padding: 5px;
width: 800px;
}
</style>
</head>
<body>
<div id="d1" class="c2"><br/><br/>
Example of replaceChild() Method<br/>
<br/>
<p id="p1" onmouseover="f1()" style="width: 300px;text-align: justify;">It is a Sample Paragraph.
Move the mouse over it to replace it with a Button</p>
<br/>
</div>
</body>
</html>
Output

Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
