HTML and CSS Reference
In-Depth Information
Just as you can add new elements to the DOM through code, you also can remove ele-
ments from the DOM using code. In this section you look at the methods available to do just
this, named removeChild and removeNode .
The removeChild method removes a child node from the calling container. This method
exists on the document object as well as other HTML container elements. The removeChild
method returns a reference to the removed node. This is especially handy if you plan to
return that node to the DOM—perhaps in response to some other user interaction with the
page. Remember, however, that if you don't keep the returned reference to the removed
node, you have no way to add the element back in without completely re-creating it. The
following example removes the first <p> element from your innerDiv element:
var innerDiv = document.getElementById("innerDiv");
var p = innerDiv.removeChild(document.getElementById("P1"));
This code provides the output in Figure 1-20. You can see that the first <p> element has
been removed. Because you captured the removed element into the variable p , you could use
it later if you wanted to put the <p> element somewhere else.
FIGURE 1-20 Removal of the first <p> element by the removeChild method
Another useful method for removing nodes or elements is removeNode , which takes one
Boolean parameter. Setting the parameter as true tells the method to do a deep removal,
which means that all children are also removed. The following code demonstrates this:
var innerDiv = document.getElementById("innerDiv");
Search WWH ::

Custom Search