Javascript Reference - HTML DOM replaceChild Method








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

The new node could be an existing node, or a new node.

Browser Support

replaceChild Yes Yes Yes Yes Yes

Syntax

node.replaceChild(newnode, oldnode)

Parameters

Parameter Type Description
newnode Node object Required. The node object to insert
oldnode Node object Required. The node object to remove




Return Value

The replaced node as Node object.

Example

The following code shows how to replace an item in a list with a new item.


<!DOCTYPE html>
<html>
<body>
<ul id="myList"><li>A</li><li>B</li><li>C</li></ul>
<button onclick="myFunction()">test</button>
<script>
function myFunction()<!--from   w w  w . j  av  a2s  .  c  om-->
{
    var textnode = document.createTextNode("D");
    var item = document.getElementById("myList").childNodes[0];
    item.replaceChild(textnode,item.childNodes[0]);
}
</script>
</body>
</html>

The code above is rendered as follows: