Replace a node in JavaScript

Description

The following code shows how to replace a node.

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><!--  w  w  w . j  a  v  a 2  s  . c o m-->
</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.firstChild);
document.writeln(returnedNode);

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

Click to view the demo

The code above generates the following result.

Replace a node 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...