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.
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:
$1.55
Once the user clicks on a cell, the HTML of the cell changes to:
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.
My technical meanderings and other nonsense. Published since 2002. No, really. I'm *that* internet-old. I remember the days of
thanks. Just what I wanted. I used the technique in a clearElements(x) function.
I “LOVE” You bro!. Thank you very much, nice funcion.
Very nice indeed. Once you have your node (in this case “cell”), you can actually right the rest as one line:
if (cell.hasChildNodes()) while (cell.childNodes.length >= 1) cell.removeChild(cell.firstChild);
You can actually cut it down even more
while(cell.hasChildNodes())
cell.removeChild(cell.firstChild);
very useful to know this though
Thanks much. If you want to remove all but the first child (or first n children), you can use:
if (cell.hasChildNodes()) while (cell.childNodes.length > n) cell.removeChild(cell.childNodes[cell.childNodes.length-1]);
Awesome – you rock man :) – now i can sleep instead of trying to figure out a way to make this thing work and staying up all night…..thanks a lot bro
Thank you. I have referred many site.at last i have found solution with your source code
Thanx Dude..
This might be better:
var cell = document.getElementById(“cell”);
while ( cell.hasChildNodes() )
{
cell.removeChild( cell.firstChild );
}
instead of:
if ( cell.hasChildNodes() )
{
while ( cell.childNodes.length >= 1 )
{
cell.removeChild( cell.firstChild );
}
}
wouldn’t
do it more succinctly?
rewrote – more generic.
Hey there… thanks for getting me on the right path for what I was looking for. I changed it up a bit and thought I’d share it back with you.
I wanted to delete only certain children, not all. so refering to firstchild didn’t work for me. Also I added a parameter of name of object for which you want to delete the children. Finally, I only am removing those that have a name (not undefined). Oh I’m throwing in my alertObject function because I use it in the other one.
function removeChildren(s){
var bDebug=true;
var o = document.getElementById(s);
var oi;
var i;
if (o){
if (bDebug==true) {alert(‘got o’);}
if ( o.hasChildNodes() )
{
if (bDebug==true) {alert(‘has’ +o.childNodes.length + ‘ children’);}
if (o.childNodes.length >= 1 )
{
for (i=0;i<=o.childNodes.length;i=i+1)
{
oi = o.childNodes[i];
if (oi.name != undefined) {
if (bDebug==true) {alertObject(‘removing: ‘ +oi.name);}
// o.removeChild(oi);
}
}
}
}
}
}
function alertObject(o){
var sLength=”";
if (o.length != undefined){
if (typeof o == ‘string’){
sLength = ”
Number of elements: 1″;
}
else{
sLength = ”
Number of elements:” + o.length;
}
}
var sMsg = “Object name: ” + o.name;
sMsg = sMsg + ”
Type: ” + typeof o;
sMsg = sMsg + ”
Type: ” + o.type;
sMsg = sMsg + ”
id: ” + o.id;
sMsg = sMsg + sLength;
alert (sMsg);
}
To the person who mentioned succinct code… that’s cool but I’d rather have code that is more readable and maintanable by others. Personal preferrence.
~Darby
Thank you very much
great script, worked first time!
I’ve wrapped it up into a neat little function …
function stripNodes(oEle) {
if ( oEle.hasChildNodes() ) {
while ( oEle.childNodes.length >= 1 ) {
oEle.removeChild( oEle.firstChild );
}
}
}
Thanks! – much nicer than el.innerHTML = ”…
Thanks! Works great!
Matthom was exactly what i’m looking for, excellent work, thanks for sharing and also thanks to carlos for the nifty tweak
Matthom was exactly what i’m looking for, excellent work, thanks for sharing and also thanks to carlos for the nifty tweak
Really easy solution… Thanks for sharing!
Why not use cell.hasChildNodes in while loop instead of the legth property?
//like this:
while(cell.hasChildNodes){
cell.removeChild(cell.firstChild);
}
MY FRIEND YOU’VE JUST ENDED 8 HOURS OF PURE AGONY! :) So far so good, have to return this thing in a couple of hours and I’m still not done but at least I can move on. If I were a girl I’d do things to you. AWESOME! MAN! AWESOME!! :)
I have been looking for a way to do this that both works in IE and Firefox for about 10 hours over the past 3 days. It works beautifully on both browsers. Thank you very much.
For me this causes an infinite loop in IE6. Or maybe I did something wrong?
ahh, never mind. It’s because I’m attempting to manipulate the object before IE is done loading. my bad.
indeed a very useful article. Just what i needed. Thanks a lot mate.
Something even cleaner/simpler; yet identical:
var el = document.getElementById(“cell”);
while ( el.hasChildNodes ) el.removeChild( el.lastChild );
If there are a lot of children, it may be more efficient to remove them last one first.
Thanks a lot. Very helpful code.
THANK YOU! I spent the last couple of days trying to figure out why my Ajax links were not working. Turns out I wasn’t removing all the childNodes to allow for the appending of new elements and nodes. I plugged in your code and it works now. I can finally get some sleep.
You rock!
Hi,
Thanks for that post. I think the subject deserved to discussed about.
Your idea was good but Bob (4th comment) did it better:
while(cell.hasChildNodes()) cell.removeChild(cell.firstChild);
I have a little bit different way for achieving the same result:
cell.innerHTML = “”;
This simply delete everything between the brackets, leaving place for new element to be appended.
Thanks a bunch! saved my morning with this little bit of code!
yup, but,.. actually, i still want which method is more efficient?
cell.innerHTML = “”;
or
while(cell.hasChildNodes()) cell.removeChild(cell.firstChild);
or
while(cell.childNodes.length) cell.removeChild(cell.firstChild);
thanks.
Thanks for sharing!
Thanks for this method, however, this recommended above is much much faster
cell.innerHTML = “”;
It’s far more efficient to remove the LAST cell rather than the first cell each time as it there will be less objects being juggled around in RAM
@plr store that method doesn’t work for form elements in IE
but you could do
cell.innerHTML = “”;
while (cell.hasChildNodes()) cell.removeChild(cell.lastChild);
it all depends on how the dom engine is written … if its design is good, it will keep ram movements to a minimum, maybe using references/pointers/whatever. as a consequence, you would get the same performances with first or last children.
generally, in an environment which naturally leads to a tree structure implementation under the hood, cutting away the root node is faster and efficent (innerhtml approach), since the dom engine, not javascript, will walk the data structure and drop each element … doing it in javascript would be a real waste of time.
but again, it all depends … to really find what is faster, you should time each approach under various circumstances, and select the best.
Dude, thanks a bunch. That little snippet saved me some time.
For those who say it doesn’t work on IE… doing the innerHTML=” IS BETTER… you just have to think a little more… you’re either using one -OR- the other.
Who said you needed to choose?
-Here, everyone’s happy:
var cell = document.getElementById('myCell'); cell.innerHTML=''; //Hopefully everything is removed and the following code won't execute. while (cell.hasChildNodes()) { //If there are still nodes present we use the long road. cell.removeChild(cell.firstChild); }Cheers…
Thank you so much for this gem. It’s helped me a ton!
Thanks, i was looking for this, i am using a combo box to insert inputs, and was not removing them, now its really nice