Chapter 9: DOM element Methods

9.3 Removing Nodes

Now that we know how to add nodes to a document, let's move on to learn how we can remove nodes from it.

To do that, we use the built-in removeChild() method. The removeChild() method takes in one argument – the name of the node to be removed. When a node is removed, all its child nodes are also removed.

To try this method, add the following code to chap9.js.

var nodeToRemove = document.getElementsByTagName("p")[0];

Here, we use the getElementsByTagName() method to select the first <p> element and assign it to a variable called nodeToRemove.

Next, let’s try to remove this node. Try adding

removeChild(nodeToRemove);

to chap9.js and run the code.

What do you get?

The node is not removed, right?

The reason for this is we need to let Javascript know which is the parent node.

Notice that the method name is removeChild(). In other words, we are trying to remove the child node of a particular parent node.

There is no method to remove a node directly, except for the removeNode() method that is not supported by most browsers and should hence be avoided.

In order to get the parent node of the node we are removing, we can use the parentNode property.

Remove the previous line and add the line below to chap9.js.

nodeToRemove.parentNode.removeChild(nodeToRemove);

Run the code again. You'll get the following output:

Javascript removeChild()
The line "Just a simple paragraph" (i.e. the first <p> element) is removed.