How To Use HTML DOM ReplaceChild Method In JavaScript

admin_img Posted By Bajarangi soft , Posted On 27-09-2020

In Java script we can replace text by another text on click of button so today we are going to discuss about how to use replacechild method in java script

How To Use HTML DOM ReplaceChild Method In JavaScript

The replaceChild() method replaces a child node with a new node.

The new node could be an existing node in the document, or you can create a new node.

Tip: Use the removeChild() method to remove a child node from an element.

Syntax and Usage

node.replaceChild(newnode, oldnode)
 

Parameter Values

newnode Node object    Required. The node object you want to insert
oldnode    Node object    Required. The node object you want to remove
 

Example(1)

<ul id="List"><li>Rose</li><li>Lotus</li><li>Hibiscus</li></ul>
<button class="btn btn-primary" onclick="flower_list()">Click it</button>
<script>
    function flower_list() {
        var textnode = document.createTextNode("Lily");
        var item = document.getElementById("List").childNodes[0];
        item.replaceChild(textnode, item.childNodes[0]);
    }
</script>

In above example when you click on the button it will replace the first item in the the list.

Example(2)
<ul id="List"><li>Rose</li><li>Lotus</li><li>Hibiscus</li></ul>
<button class="btn btn-primary" onclick="flower_list()">Click it</button>

<script>
    function flower_list() {
        var element = document.createElement("li");
        var textnode = document.createTextNode("Lily");
        element.appendChild(textnode);

        var item = document.getElementById("List");
        item.replaceChild(element, item.childNodes[0]);
    }
</script>

In above example when you click on the button it will replace the first item in the the list..

Complete code for HTML DOM ReplaceChild Method In JavaScript
<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM ReplaceChild Method In JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
    h1 {
        color: red;
    }
    li{
        font-size: 30px;
    }
</style>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>HTML DOM ReplaceChild Method In JavaScript</h1>
    </div>
    <br>
    <div class="well">
        <ul id="List"><li>Rose</li><li>Lotus</li><li>Hibiscus</li></ul>
        <button class="btn btn-primary" onclick="flower_list()">Click it</button>
    </div>
    <br>
</div>
</body>
</html>
<script>
    function flower_list() {
        var textnode = document.createTextNode("Lily");
        var item = document.getElementById("List").childNodes[0];
        item.replaceChild(textnode, item.childNodes[0]);
    }
</script>

 

Related Post