The replaceChild()
method replaces a child node with a new node.
The new node could be an existing node, or a new node.
replaceChild |
Yes | Yes | Yes | Yes | Yes |
node.replaceChild(newnode, oldnode)
Parameter | Type | Description |
---|---|---|
newnode | Node object | Required. The node object to insert |
oldnode | Node object | Required. The node object to remove |
The replaced node as Node object.
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: