1. Technology

Your suggestion is on its way!

An email with a link to:

http://javascript.about.com/library/bldom09.htm

was emailed to:

Thanks for sharing About.com with others!

The Javascript DOM

9. removeChild

clr gif

So far we have looked at how to use the various commands that the DOM makes available to us to access various parts of our web page and we have looked at the non-standard but widely supported innerHTML method of updating part of a web page.

Now it is time to start looking at the standard methods that the DOM makes available to update the content of a web page. These combinations of commands can become quite complex depending on just what it is that you are trying to do so we'll start with some of the simpler things and build up to the more complex ones gradually. Probably the simplest of the standard DOM update commands is removeChild.

The removeChild method is used to remove a container from our web page. There are two steps to being able to do this. The first thing that we need to do is to use one of the methods that we have already learned to obtain a reference to the container within the web page that we wish to remove. The second step is to pass that reference to the removeChild method on a parent of the container to be removed.

For example, let's say that we want to remove the second paragraph within our web page. The following code will do this for us.

var p2 = document.getElementsByTagName('p')[1];
p2.parentNode.removeChild(p2);

We already know that getElementsByTagName returns an array of all of the containers of a particular type as an array so the first line of our code returns an array of all of the paragraphs. Since the paragraph we want is the second one and the first element in Javascript arrays is always 0 we simply need to reference [1] to get the second paragraph. We assign this to an object called p2 (since it is the second paragraph).

The second line is our new code that will delete the specified paragraph from the page. The parentNode property gets us to the parent of the current container and the removeChild method then removes the specified child container from within that parent. The combination of parentNode and removeChild ensures that we are referencing the removeChild method on the actual parent of the container that we wish to remove.

©2014 About.com. All rights reserved.