Javascript DOM HTML Node replaceChild Method replace <LI> element

Introduction

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

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() {//  w  ww.j av 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>



PreviousNext

Related