Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Removing all child nodes from an element

  Matt Thommes        2011-10-19 10:04:23       3,139        0    

When manipulating the DOM, it's often useful to remove all child nodes from a specific element. This typically comes in handy when you're looking to replace the content of an element with a separate form element, such as an <input>, so the user can edit the actual value.

Here's an example of something I recently created that illustrates my point:

Get the Flash Player to see this player.

These "dynamic form elements" are written to the page only when the user performs a certain action; in this case: clicking on a table cell.

The HTML for the table cell could look something like this:

<td id="cell">$1.55</td>

Once the user clicks on a cell, the HTML of the cell changes to:

<td id="cell"><input type="text" value="$1.55" /></td>

This gives the user a text box with which to edit the value.

In order to do this, you'll need a quick way to remove any existing child nodes of the table cell.

There are many ways to do this in JavaScript, but I've discovered one that seems to work in all types of situations:

var cell = document.getElementById("cell");

if ( cell.hasChildNodes() )
{
    while ( cell.childNodes.length >= 1 )
    {
        cell.removeChild( cell.firstChild );       
    } 
}

No matter how many nested nodes exist, it removes them all. Quite handy.

Source:http://matthom.com/archive/2007/05/03/removing-all-child-nodes-from-an-element

JS  DOM  REMOVE ALL CHILDREN  CLEAR  JAVASCRIPT  CODE 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.