Polaris878 Polaris878 - 1 year ago 167
Javascript Question

Remove all child elements of a DOM node in JavaScript

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">

And I grab the node I want like so:

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

How could I remove the children of
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

I'd like the answer to be straight up DOM; though extra points if you also provide an answer in jQuery along with the DOM-only answer.

Answer Source

Option 1 (much slower, see comments below):

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

Option 2 (much faster):

var myNode = document.getElementById("foo");
while (myNode.firstChild) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download