Javascript DOM HTML Node replaceChild Method

Introduction

Replace a text node in a <li> element in a list with a new text node:

Click the button to replace the first item in the the list.

View in separate window

<!DOCTYPE html>
<html>
<body>

<ul id="myList"><li>CSS</li><li>HTML</li><li>Java</li></ul>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {//from   www  . j a v  a  2 s . c  o  m
  var textnode = document.createTextNode("Water");
  var item = document.getElementById("myList").childNodes[0];
  item.replaceChild(textnode, item.childNodes[0]);
}
</script>

</body>
</html>

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.

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

replaceChild(newnode, oldnode);

Parameter Values

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

The replaceChild() method returns a Node object representing the replaced node.




PreviousNext

Related