Removing Nodes from the DOM

Contact Us or call 1-877-932-8228
Removing Nodes from the DOM

Removing Nodes from the DOM

Element nodes have a removeChild() method, which takes a single parameter: the child node to be removed. There is no W3C method for a node to remove itself, but the following function will do the trick:

function removeElement(elem) {

removeChild(elem) only removes the element from its parent. Setting elem to null destroys the element.

Sometimes it's useful to remove all of a node's children in one fell swoop. The function below will handle this:

function removeAllChildren(parent) {	
	while (parent.hasChildNodes()) {

Both of these functions are in our ClassFiles/lib.js library.

DOM Differences: The Whitespace Problem

The W3C specification is not entirely clear on how certain whitespace should be treated in the DOM. For example, Internet Explorer also ignores whitespace that occurs between open and close tags (e.g, <td> </td>). This is just plain wrong, but it doesn't generally create problems.

The whitespace in question is any that occurs between a close tag and an open tag (e.g, </tr> <tr>), between two open tags (e.g, <tr> <td>), or between two close tags (e.g, </td> </tr>). The question is: should this whitespace be preserved or ignored in the DOM. The answer, it turns out, is unclear; however, the way a browser treats this space is very important. To illustrate, open HTMLDOM/Demos/Hierarchy.html in Internet Explorer 8 or earlier and click on the middle list item. You will get the following message:Internet Explorer Message

Notice that the nextSibling and previousSibling properties both reference list item nodes, whereas they referenced text nodes in Firefox. If you were to click on the ul element itself, you would find that Internet Explorer 8 and earlier consider it to have three child nodes (the list items), whereas Firefox and other modern browsers (including Internet Explorer 9) consider it to have seven. Firefox counts the whitespace-only text nodes. Internet Explorer 8 and earlier do not.

For a lengthy discussion on this topic, see