Replace the last child in JavaScript

Description

The following code shows how to replace the last child.

Example


<!DOCTYPE html>
<html>
<body>
<div id="div1">
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul><!--from ww  w.j a va  2s . c  om-->
</div>
<p id="p1">Hello <b>World!</b></p>


<script type="text/javascript">
var div = document.getElementById("div1");
var p = document.getElementById("p1");

var returnedNode = div.replaceChild(p, div.lastChild);
document.writeln(returnedNode);

</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Replace the last child in JavaScript
Home »
  Javascript Tutorial »
    DOM »
      Update
Javascript Tutorial Update
Add and set new attribute for new created H...
Change attribute value for a HTML element i...
Replace a node in JavaScript
Replace the last child in JavaScript
Replace the text for a paragraph in JavaScr...
Set the inner text for a HTML element in Ja...
Set the outer html for a HTML element in Ja...
Update child element recursively in JavaScr...
Update the inner html for a HTML element in...
Use element's inner html to show the result...