Element replaceChild Method - Javascript DOM

Javascript examples for DOM:Element replaceChild

Description

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

Syntax

element.replaceChild(newnode,oldnode);

Parameter Values

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

Return Value:

A Node object, representing the replaced node

The following code shows how to Replace a text node in a <li> element in a list with a new text node:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {//  w  ww .  j a v a  2 s. co m
    var elmnt = document.createElement("li");
    var textnode = document.createTextNode("Water");
    elmnt.appendChild(textnode);

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

</body>
</html>

Related Tutorials