tags:

views:

107

answers:

5

How would I go about removing all of the child elements of a DOM node in JavaScript?

Say I have the following (ugly) HTML:

<p id="foo">
    <span>hello</span>
    <div>world</div>
</p>

And I grab the node I want like so:

var myNode = document.getElementById("foo");

How could I remove the children of foo so that just <p id="foo"></p> is left?

Could I just do:

myNode.childNodes = new Array();

or should I be using some combination of removeElement?

I'd like to keep this answer to straight up DOM if possible, though if you supplement your answer with jQuery I'd be more amenable to accepting your answer :).

+7  A: 

Option 1:

var myNode = document.getElementById("foo");
myNode.innerHTML = '';

Option 2:

var myNode = document.getElementById("foo");
while (myNode.firstChild) {
    myNode.removeChild(myNode.firstChild);
}
Gabriel McAdams
+1: As I understand it, using innerHTML performs much better than removing the children individually. That said, if you are working with about the XML DOM rather than the HTML DOM, you need to do things another way.
idealmachine
innerHTML seems not working sometimes
jebberwocky
@Jebberwocky: what do you mean? What does sometimes mean? And what does not working mean?
Gabriel McAdams
A: 

Hello,

with jQuery :

$("#foo").find("*").remove();
Arnaud F.
Look at the end of his post "though if you supplement your answer with jQuery I'd be more amenable to accepting your answer :)."
Arnaud F.
@meagar, the OP asks for it as well..
Gaby
Can be done much shorter as `$('#foo').empty();`.
idealmachine
Yes, I read that and removed my down-vote.
meagar
+1  A: 
var myNode = document.getElementById("foo");
var fc = myNode.firstChild;

while( fc ) {
    myNode.removeChild( fc );
    fc = myNode.firstChild;
}

If there's any chance that you have jQuery affected descendants, then you must use some method that will clean up jQuery data.

$('#foo').empty();

The jQuery .empty() method will ensure that any data that jQuery associated with elements being removed will be cleaned up.

If you simply use DOM methods of removing the children, that data will remain.

patrick dw
+1  A: 

In jQuery:

$('#foo').empty();
idealmachine
+1  A: 

If you only want to have the node without it's children you could also make a copy of it like this:

var dupNode = document.getElementById("foo").cloneNode(false);

Depends on what you're trying to achieve.

DanMan