1. Computing

JavaScript By Example

Document Object Model: 16. Remove A Node

By

In addition to being able to access the attributes and styles associated with a node and to be able to replace all child nodes with a text string, we can also perform updates on the node itself. The simplest such update is to delete the node from the web page completely. We do this by calling the removeChild method on the parent of the node to be removed passing the node into the method as a parameter. Removing a node from the page also removes all of the child nodes contained within that node.

This example demonstrates how we can remove a div tag from our web page including whatever is contained within the div.

Note that content added to the web page using innerHTML does not create nodes and so you cannot remove tags from within any content generated using innerHTML through this method. If you want to be able to treat the added content the same way as the existing content then you cannot use innerHTML and must instead use the proper DOM methods.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D16</title>
</head>
<body>
<div id="ex">This content ti be removed.</div>
<script type="text/javascript" src="exampleD16.js"></script>
</body>
</html>

JavaScript


var dv;
dv = document.getElementById('ex');
dv.parentNode.removeChild(dv);

  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM: Remove A Node

©2014 About.com. All rights reserved.