Child Nodeleri Silmek

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 , so the user can edit the actual value
www.dijitalders.comHere's an example of something I recently created that illustrates my point

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">.55</td>

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

<td id="cell"><input type="text" value=".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.

Kaynak http://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 , so the user can edit the actual value.

Yorumunuzu Ekleyin


Yükleniyor...
Yükleniyor...