Remove all child elements of a DOM node in JavaScript
Asked Answered
Z

39

1374

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 the answer to be straight up DOM; though extra points if you also provide an answer in jQuery along with the DOM-only answer.

Zymogenic answered 17/10, 2010 at 20:51 Comment(0)
L
546

In 2022+, use the replaceChildren() API!

Replacing all children can now be done with the (cross-browser supported) replaceChildren API:

container.replaceChildren(...arrayOfNewChildren);

This will do both:

  • remove all existing children, and
  • append all of the given new children, in one operation.

You can also use this same API to just remove existing children, without replacing them:

container.replaceChildren();

This is fully supported in Chrome/Edge 86+, Firefox 78+, and Safari 14+. It is fully specified behavior. This is likely to be faster than any other proposed method here, since the removal of old children and addition of new children is done without requiring innerHTML, and in one step instead of multiple.

Lamia answered 22/12, 2020 at 18:17 Comment(12)
The MDN data has now been corrected, and shows full cross-browser support: caniuse.com/?search=replacechildrenLamia
This is significantly slower than the other methods mentioned here, at least for me.Spillman
Would you mind linking to your test, and the details like which browser/platform you used? That would surprise me greatly, at least on Chrome.Lamia
Don't do this. It may seem nice but will trigger a separate MutationRecord for each removed child (when using a MutationObserver on the element). Setting textContent is much faster for hundreds of children. (I mean you can do this, but always set textContent to remove many existing children first.)Intermix
@ygoe, that should not be the case. Can you show an example? Here is my example code: jsbin.com/xopapef, which uses a target element containing 10,000 children. At least in Chrome, it shows exactly one mutation observer call in both cases. Do you see something different? If so, please clarify what browser and platform you're using. (My demo, at least for me, also shows that replaceChildren() is at least as fast, and is typically faster, than textContent.)Lamia
I ran the site I linked above on a Mac, on Chrome, Firefox, and Safari, and all three agree: only one mutation observer call. And replaceChildren() is very slightly faster on all three. Let me know if you see something different.Lamia
Well, in a simple demo case, it looks good indeed. But in my application it results in that behaviour. Setting textContent = "" before calling replaceChildren(...newChildren) resolves the issue completely. Since mutation observer events are asynchronous, I cannot determine what the causing code is. But I'm happy with my working code. Others might need to inspect their own situation close enough to decide themselves.Intermix
Ok. If you can post a minimized version of your problem code as a bug (crbug.com/new), I could take a closer look.Lamia
Changing this to the accepted answer, since it's now the suggested modern approach :)Zymogenic
It is slowest variant even tested. At least what I got in Firefox.Kalgan
Interesting! On the test site I linked above? Or something else?Lamia
This stopped working for some reason.Octillion
L
2312

Option 1 A: Clearing innerHTML.

  • This approach is simple, but might not be suitable for high-performance applications because it invokes the browser's HTML parser (though browsers may optimize for the case where the value is an empty string).

doFoo.onclick = () => {
  const myNode = document.getElementById("foo");
  myNode.innerHTML = '';
}
<div id='foo' style="height: 100px; width: 100px; border: 1px solid black;">
  <span>Hello</span>
</div>
<button id='doFoo'>Remove via innerHTML</button>

Option 1 B: Clearing textContent

  • As above, but use .textContent. According to MDN this will be faster than innerHTML as browsers won't invoke their HTML parsers and will instead immediately replace all children of the element with a single #text node.

doFoo.onclick = () => {
  const myNode = document.getElementById("foo");
  myNode.textContent = '';
}
<div id='foo' style="height: 100px; width: 100px; border: 1px solid black;">
  <span>Hello</span>
</div>
<button id='doFoo'>Remove via textContent</button>

Option 2 A: Looping to remove every lastChild:

  • An earlier edit to this answer used firstChild, but this is updated to use lastChild as in computer-science, in general, it's significantly faster to remove the last element of a collection than it is to remove the first element (depending on how the collection is implemented).
  • The loop continues to check for firstChild just in case it's faster to check for firstChild than lastChild (e.g. if the element list is implemented as a directed linked-list by the UA).

doFoo.onclick = () => {
  const myNode = document.getElementById("foo");
  while (myNode.firstChild) {
    myNode.removeChild(myNode.lastChild);
  }
}
<div id='foo' style="height: 100px; width: 100px; border: 1px solid black;">
  <span>Hello</span>
</div>
<button id='doFoo'>Remove via lastChild-loop</button>

Option 2 B: Looping to remove every lastElementChild:

  • This approach preserves all non-Element (namely #text nodes and <!-- comments --> ) children of the parent (but not their descendants) - and this may be desirable in your application (e.g. some templating systems that use inline HTML comments to store template instructions).
  • This approach wasn't used until recent years as Internet Explorer only added support for lastElementChild in IE9.

doFoo.onclick = () => {
  const myNode = document.getElementById("foo");
  while (myNode.lastElementChild) {
    myNode.removeChild(myNode.lastElementChild);
  }
}
<div id='foo' style="height: 100px; width: 100px; border: 1px solid black;">
  <!-- This comment won't be removed -->
  <span>Hello <!-- This comment WILL be removed --></span>
  <!-- But this one won't. -->
</div>
<button id='doFoo'>Remove via lastElementChild-loop</button>

Bonus: Element.clearChildren monkey-patch:

  • We can add a new method-property to the Element prototype in JavaScript to simplify invoking it to just el.clearChildren() (where el is any HTML element object).
  • (Strictly speaking this is a monkey-patch, not a polyfill, as this is not a standard DOM feature or missing feature. Note that monkey-patching is rightfully discouraged in many situations.)

if( typeof Element.prototype.clearChildren === 'undefined' ) {
    Object.defineProperty(Element.prototype, 'clearChildren', {
      configurable: true,
      enumerable: false,
      value: function() {
        while(this.firstChild) this.removeChild(this.lastChild);
      }
    });
}
<div id='foo' style="height: 100px; width: 100px; border: 1px solid black;">
  <span>Hello <!-- This comment WILL be removed --></span>
</div>
<button onclick="this.previousElementSibling.clearChildren()">Remove via monkey-patch</button>
Lazy answered 17/10, 2010 at 20:52 Comment(27)
From jQuery these two issues might be considered: This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element. AND "To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves."Laudanum
@micha I think your test is not right. I have written my one on jsfidle (jsfiddle.net/6K6mv/5) and here is the result. WHILE: 14ms; INNERHTML: 7ms; TEXTCONTENT: 7msBergeman
@m93a: running your fiddle multiple times gives me results all over the place between 6ms to 11ms. This is basically telling me nothing. The results are closer together than the variance in ms between each testrun for the same test. For the record: It's not MY script, its jsperf.com. Look at this for a better understanding of the test results: https://mcmap.net/q/46353/-explain-this-jsperf-com-result and https://mcmap.net/q/46352/-how-does-jsperf-determine-which-of-the-code-snippets-is-fastest/…Muddle
@Muddle Yes, I know what the test results mean, but it seems strange. It shows me thas innerHTML is 98% - 99% slower. And my tests show the opposite. But this is not a chat, I'm leaving discussion.Bergeman
innerHTML only works if you are only dealing with HTML. If there is e.g. SVG inside only Element removal will workPetula
NEVER NEVER NEVER use innerHTML = ''. Don't. The problem is that the items look like they're removed but internally, nodes persist and slow things down. You have to remove all the individual nodes for a reason. Tested in both Google Chrome and IE. Please consider removing the innerHTML "solution" since it's wrong.Topazolite
@Muddle jsperf.com/innerhtml-vs-removechild/151 using .remove() is even faster.Bolan
@joeytje50 Nice one! Unfortunately it's DOM4 and not available everywhere. I'm sticking with .removeChild() for better compatibility. Besides, the gain of .remove() is only 2%.Muddle
I put this in a prototype so I could use it more easily: Element.prototype.clear = function(){while (this.firstChild) {this.removeChild(this.firstChild);}}Bewray
@Topazolite - what if I do document.documentElement.replaceChild(newBody, document.body) ? would the "old" elements and their events persist in memory? (when replacing the whole body element)Karmenkarna
@Andrey Lushnikov: Depends on which browser and which version. Actually firstChild ist best overall: jsperf.com/innerhtml-vs-removechild/250Chalco
@Karmenkarna I don't believe Kenji's comment is well-founded. Doing innerHTML = '' is slower, but I don't think it's "wrong". Any claims of memory leaks should be backed up with evidence.Douglassdougy
@Andrey Lushnikov firstChild and lastChild are pretty equivalent on my Chrome 43.0.2357.52 (first run removeChildFirst was a little faster, second run removeChildLast won), but both are winners over innerHTML.Lanta
@Kenji, Surely the browser is smart enough to prevent a memory leak. Have you managed to cause a memory leak in the browser?Breaking
Your examples aren't wrong, but I think there's a pretty good case in this answer that the jsperf test was flawed, and didn't measure what it's supposed to. (The claim in the linked answer is that they were only removing empty divs, as they erroneously assumed that the DOM would be repopulated between each test.) In other words, innerHTML is faster, and there's an even faster method (replacing nodes with empty ones). Since your answer is so highly upvoted, it would be nice if you'd revert that part.Affrica
@Bewray Proceed with care and make sure your target audience's browsers work with it. perfectionkills.com/whats-wrong-with-extending-the-domChihli
function emptyElement(element) { var myNode = element; while (myNode.firstChild) { myNode.removeChild(myNode.firstChild); } } emptyElement(document.body)Unconnected
(assuming its true) it would be nice to have the reason in the answerIdeatum
I tried myNode.childNodes.forEach(function (c) { c.remove() }), but this doesn't remove all the children. I realize some browsers don't support the method, but for the browsers that do support it, it doesn't remove all the nodes. Why does the while loop work better than NodeList#forEach()?Antimalarial
@Antimalarial You are modifying a collection that you are actively iterating over when you use forEach in that manner.Jessikajessup
This is ridiculous. Why performance matters here? Is it 120 fps or one-off operation?Skeet
I agree with @MichalStefanow. In this case, simplicity of code should precede the minimal performance gain, unless you are working on a specific scenario that requires this level of meticulous optimization. It will not make a difference when removing 5-15 nodes.Moneybag
As a new web developer, just wanna say u sir are a god. Thanks for both the methods. I have been playing around with both!Gough
remove gives an infinite loop for me on Brave 80.1.5.123. removeChild works fineNorthwester
If I have 10 children elements I want to remove and each of them has an event attached to it, should I remove the event first then element itself or I don't need to remove the event, I can just remove the element itself??(vanilla javascript)Fleury
Concerning @stwissel’s remark about innerHTML not working on SVG elements: that was fixed across all browsers by the start of 2015, except of course for IE that was no longer being developed by then (only maintained). So long as you’re not supporting IE11 (which you actively shouldn’t, let it die!), you can happily use innerHTML on SVG elements.Mcneely
I feel like this answer should be edited to list textContent first, since that's the faster and safer optionAccroach
L
546

In 2022+, use the replaceChildren() API!

Replacing all children can now be done with the (cross-browser supported) replaceChildren API:

container.replaceChildren(...arrayOfNewChildren);

This will do both:

  • remove all existing children, and
  • append all of the given new children, in one operation.

You can also use this same API to just remove existing children, without replacing them:

container.replaceChildren();

This is fully supported in Chrome/Edge 86+, Firefox 78+, and Safari 14+. It is fully specified behavior. This is likely to be faster than any other proposed method here, since the removal of old children and addition of new children is done without requiring innerHTML, and in one step instead of multiple.

Lamia answered 22/12, 2020 at 18:17 Comment(12)
The MDN data has now been corrected, and shows full cross-browser support: caniuse.com/?search=replacechildrenLamia
This is significantly slower than the other methods mentioned here, at least for me.Spillman
Would you mind linking to your test, and the details like which browser/platform you used? That would surprise me greatly, at least on Chrome.Lamia
Don't do this. It may seem nice but will trigger a separate MutationRecord for each removed child (when using a MutationObserver on the element). Setting textContent is much faster for hundreds of children. (I mean you can do this, but always set textContent to remove many existing children first.)Intermix
@ygoe, that should not be the case. Can you show an example? Here is my example code: jsbin.com/xopapef, which uses a target element containing 10,000 children. At least in Chrome, it shows exactly one mutation observer call in both cases. Do you see something different? If so, please clarify what browser and platform you're using. (My demo, at least for me, also shows that replaceChildren() is at least as fast, and is typically faster, than textContent.)Lamia
I ran the site I linked above on a Mac, on Chrome, Firefox, and Safari, and all three agree: only one mutation observer call. And replaceChildren() is very slightly faster on all three. Let me know if you see something different.Lamia
Well, in a simple demo case, it looks good indeed. But in my application it results in that behaviour. Setting textContent = "" before calling replaceChildren(...newChildren) resolves the issue completely. Since mutation observer events are asynchronous, I cannot determine what the causing code is. But I'm happy with my working code. Others might need to inspect their own situation close enough to decide themselves.Intermix
Ok. If you can post a minimized version of your problem code as a bug (crbug.com/new), I could take a closer look.Lamia
Changing this to the accepted answer, since it's now the suggested modern approach :)Zymogenic
It is slowest variant even tested. At least what I got in Firefox.Kalgan
Interesting! On the test site I linked above? Or something else?Lamia
This stopped working for some reason.Octillion
W
168

Use modern Javascript, with remove!

const parent = document.getElementById("foo")
while (parent.firstChild) {
    parent.firstChild.remove()
}

This is a newer way to write node removal in ES5. It is vanilla JS and reads much nicer than relying on parent.

All modern browsers are supported.

Browser Support - 97% Jun '21

Witticism answered 15/11, 2016 at 9:57 Comment(4)
The for loop will not work since parent.children / parent.childNodes are live lists; calling remove modifies the list and your iterator therefore isn't guaranteed to iterate over everything. In chrome, e.g., you end up skipping every other node. Better to use a while (parent.firstChild) { parent.removeChild(parent.firstChild); } loop. developer.mozilla.org/en-US/docs/Web/API/ParentNode/children developer.mozilla.org/en-US/docs/Web/API/Node/childNodesAlric
Cool shorthand, although less readable: while (parent.firstChild && !parent.firstChild.remove());Witticism
A one-liner for when performance isn't a huge deal: [...parent.childNodes].forEach(el => el.remove());Herb
This does not work in Typescript... instead use while (selectElem.firstElementChild) { selectElem.firstElementChild.remove(); }Ellita
M
141

The currently accepted answer is wrong about innerHTML being slower (at least in IE and Chrome), as m93a correctly mentioned.

Chrome and FF are dramatically faster using this method (which will destroy attached jquery data):

var cNode = node.cloneNode(false);
node.parentNode.replaceChild(cNode, node);

in a distant second for FF and Chrome, and fastest in IE:

node.innerHTML = '';

InnerHTML won't destroy your event handlers or break jquery references, it's also recommended as a solution here: https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML.

The fastest DOM manipulation method (still slower than the previous two) is the Range removal, but ranges aren't supported until IE9.

var range = document.createRange();
range.selectNodeContents(node);
range.deleteContents();

The other methods mentioned seem to be comparable, but a lot slower than innerHTML, except for the outlier, jquery (1.1.1 and 3.1.1), which is considerably slower than anything else:

$(node).empty();

Evidence here:

http://jsperf.com/innerhtml-vs-removechild/167 http://jsperf.com/innerhtml-vs-removechild/300 https://jsperf.com/remove-all-child-elements-of-a-dom-node-in-javascript (New url for jsperf reboot because editing the old url isn't working)

Jsperf's "per-test-loop" often gets understood as "per-iteration", and only the first iteration has nodes to remove so the results are meaningless, at time of posting there were tests in this thread set up incorrectly.

Macaluso answered 9/4, 2014 at 15:4 Comment(16)
Your jsperf is completely broken. That's not very good evidence.Wapiti
Thanks for noting that, fixed it, insertBefore spec changed and no longer takes undefined for last param.Macaluso
This is currently the best answer. Everything else in this thread is disinformation (!) Thanks for cleaning up all those bad old tests.Polyhymnia
"InnerHTML won't destroy your event handlers or mess up any jquery references" It will orphan data held in jQuery.cache, causing a memory leak because the only reference available to manage that data was on the elements you just destroyed.Amaris
"InnerHTML won't destroy your event handlers or mess up any jquery references" refers to the container, not the children. cloneNode switches out the container, which means references to the container are not maintained (jquery or otherwise). Jquery's cache may make it worth using jquery to remove elements if you have jquery data attached to them. Hopefully they switch to WeakMaps at some point. Cleaning (or even the existence of) the $.cache doesn't appear to be officially documented.Macaluso
jsperf offline, would you mind uploading you test-code here, if you have it? I'd appriciate that!Bouillon
I don't have code, but jsperf is in the waybackmachine web.archive.org/web/20151008164028/http://jsperf.com/…Macaluso
Just a random query: why does your benchmark include code for setting up the data that is going to be removed inside the benchmarked section? Surely the setup should be done outside of the benchmark, but all of your benchmarks call refreshRange() (which clones a set of test data into a new node) from within the test. How can you be sure that this isn't skewing the results?Sialoid
Also, why are you using contents().remove() in your jquery tests (which builds an internal list of all of the child nodes and then removes them) rather than empty() (which just removes them)?Sialoid
Still not a proper benchmark imo. nodes should be generated with attached events, attributes, functions, etc... for a more realistic benchmark. It kind of make sense that removeChild will remove attached resources while innerHTML might not, thus being slower, but if you benchmark without any attached resources it does not make sense.Talton
@PeriataBreatta The jsperf comments are lost, but what I was referring to about broken-ness was only performing removal once per test. Jsperf's "per-test-loop" often gets understood as "per-iteration", and then only the first iteration does any work and the results are meaningless. It would be ideal to set up outside of iteration, but as long as the setup is the same and minimized, the relative results are meaningful. I didn't know about empty(), thanks for the heads up, I'll fix it.Macaluso
@GregoireD. That info isn't really requested in the question, and I think the bigger concern for innerHTML usage in removing nodes is probably memory leaks more than performance, and throwing a leaky test premise in jsperf which has no ability to clean per-iteration would probably end up skewing the resultsMacaluso
The jsperf tests are broken here. The test engine reports the following: "Error: Dom nodes not recreated during iterations, test results will be meaningless."Homogeneity
cloneNode(false) is indeed superfast, but the problem is since it's destructive, you'll have to re-reference your variables, which is a big penalty, e.g.: jsperf.com/innerhtml-vs-removechild/467Lanta
I'm working on a DOM course and since it looks like jsperf.com is mia and might be for a while, I created a page on jsben.ch. As of today, innerHTML is still the winner. I've spent too long on this rabbit hole already, but in the year 2020 I have to wonder why we don't have a .clear() or .empty() DOM method yet...Pyroclastic
just set .textContent to "". according to the spec, this is treated as a special case: dom.spec.whatwg.org/#string-replace-allAccroach
A
48

If you use jQuery:

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

If you don't:

var foo = document.getElementById('foo');
while (foo.firstChild) foo.removeChild(foo.firstChild);
Aliaalias answered 17/10, 2010 at 21:2 Comment(0)
B
47
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.

Bobbybobbye answered 17/10, 2010 at 20:57 Comment(3)
The innerHTML method is by far the most performant. That said, the data being cleaned up by jquery's .empty(): Eliminates the data() inside jquery associated with the child tags using a recursive loop (slow, but may reduce memory usage significantly), Prevents memory leaks IF you attached events without jquery, like using .onclick=... . If you have no such events in the children to be removed, then setting innerHTML won't leak. So the best answer is - it depends.Saran
Why not just put the firstChild expression directly in the condition of the while loop? while ( myNode.firstChild ) {Breastsummer
while(fc = myNode.firstChild){ myNode.removeChild(fc); }Woolgrower
P
28

Use elm.replaceChildren().

It’s experimental without wide support, but when executed with no params will do what you’re asking for, and it’s more efficient than looping through each child and removing it. As mentioned already, replacing innerHTML with an empty string will require HTML parsing on the browser’s part.

MDN Documentation

Update It's widely supported now

Piatt answered 28/7, 2020 at 8:5 Comment(2)
caniuse.com/?search=replaceChildren Latest version of Chrome and Safari just got it. Give it a couple months. God I love auto-updates.Piatt
How much HTML parsing happens on an empty string?Bugeye
D
25

The fastest...

var removeChilds = function (node) {
    var last;
    while (last = node.lastChild) node.removeChild(last);
};

Thanks to Andrey Lushnikov for his link to jsperf.com (cool site!).

EDIT: to be clear, there is no performance difference in Chrome between firstChild and lastChild. The top answer shows a good solution for performance.

Dulcinea answered 2/4, 2013 at 18:2 Comment(1)
Same thing without LINT warning: clear: function ( container ) { for ( ; ; ) { var child = container.lastChild; if ( !child ) break; container.removeChild( child ); } }Han
R
10

If you only want to have the node without its 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.

Relativistic answered 17/10, 2010 at 21:13 Comment(3)
Maybe you could even follow this with parent.replaceChild(cloned, original)? That might be faster than removing children one by one and should work on everything that supports the DOM (so every type of XML document, including SVG). Setting innerHTML might also be faster than removing children one by one, but that doesn't work on anything but HTML documents. Should test that some time.Rheumatism
That won't copy event listeners added using addEventListener.Alodee
If you can live with that limitation, it's certainly quick: jsperf.com/innerhtml-vs-removechild/137Relativistic
P
9

Ecma6 makes it easy and compact

myNode.querySelectorAll('*').forEach( n => n.remove() );

This answers the question, and removes “all child nodes”.

If there are text nodes belonging to myNode they can’t be selected with CSS selectors, in this case we’ve to apply (also):

myNode.textContent = '';

Actually the last one could be the fastest and more effective/efficient solution.

.textContent is more efficient than .innerText and .innerHTML, see: MDN

Parasynthesis answered 12/11, 2020 at 8:29 Comment(0)
C
8

Here's another approach:

function removeAllChildren(theParent){

    // Create the Range object
    var rangeObj = new Range();

    // Select all of theParent's children
    rangeObj.selectNodeContents(theParent);

    // Delete everything that is selected
    rangeObj.deleteContents();
}
Chaisson answered 11/3, 2014 at 20:27 Comment(1)
This is interesting but it seems fairly slow compared to other methods: jsperf.com/innerhtml-vs-removechild/256Zymogenic
I
8
element.textContent = '';

It's like innerText, except standard. It's a bit slower than removeChild(), but it's easier to use and won't make much of a performance difference if you don't have too much stuff to delete.

Intercept answered 28/3, 2014 at 17:13 Comment(3)
A text node is not an elementShamefaced
sorry you're right, it removes indeed all children elementsShamefaced
This won't work in older versions of Internet Explorer.Minter
K
8

I reviewed all questions and decided to test performance for most crucial test case:

  • we need to clear content
  • we need to keep original element
  • we need to delete a lot of child elements

So my HTML:

<div id="target">
  <div><p>Title</p></div>
  <!-- 1000 at all -->
  <div><p>Title</p></div>
</div>
// innerHTML
target.innerHTML = "";
// lastChild
while (target.hasChildNodes()) {
    target.removeChild(target.lastChild);
}
// firstChild
while (target.hasChildNodes()) {
    target.removeChild(target.firstChild);
}
// replaceChildren
target.replaceChildren();
Results:
Checked test: innerHTML x 1,222,273 ops/sec ±0.47% (63 runs sampled)
Checked test: lastChild x 1,336,734 ops/sec ±0.87% (65 runs sampled)
Checked test: firstChild x 1,313,521 ops/sec ±0.74% (64 runs sampled)
Checked test: replaceChildren x 743,076 ops/sec ±1.08% (53 runs sampled)

Checked test: innerHTML x 1,202,727 ops/sec ±0.83% (63 runs sampled)
Checked test: lastChild x 1,360,350 ops/sec ±0.72% (65 runs sampled)
Checked test: firstChild x 1,348,498 ops/sec ±0.78% (63 runs sampled)
Checked test: replaceChildren x 743,076 ops/sec ±0.86% (53 runs sampled)

Checked test: innerHTML x 1,191,838 ops/sec ±0.73% (62 runs sampled)
Checked test: lastChild x 1,352,657 ops/sec ±1.42% (63 runs sampled)
Checked test: firstChild x 1,327,664 ops/sec ±1.27% (65 runs sampled)
Checked test: replaceChildren x 754,166 ops/sec ±1.88% (61 runs sampled)
Conclusions

Modern API is most slow. First child and last child ways are equal, some side effect can be present if comparison happens with multiple cases. But side by side you can see here:

Checked test: firstChild x 1,423,497 ops/sec ±0.53% (63 runs sampled)
Checked test: lastChild x 1,422,560 ops/sec ±0.36% (66 runs sampled)

Checked test: firstChild x 1,368,175 ops/sec ±0.57% (65 runs sampled)
Checked test: lastChild x 1,381,759 ops/sec ±0.39% (66 runs sampled)

Checked test: firstChild x 1,372,109 ops/sec ±0.37% (66 runs sampled)
Checked test: lastChild x 1,355,811 ops/sec ±0.35% (65 runs sampled)
Checked test: lastChild x 1,364,830 ops/sec ±0.65% (64 runs sampled)
Checked test: firstChild x 1,365,617 ops/sec ±0.41% (65 runs sampled)

Checked test: lastChild x 1,389,458 ops/sec ±0.50% (63 runs sampled)
Checked test: firstChild x 1,387,861 ops/sec ±0.40% (64 runs sampled)

Checked test: lastChild x 1,388,208 ops/sec ±0.43% (65 runs sampled)
Checked test: firstChild x 1,413,741 ops/sec ±0.47% (65 runs sampled)

P.S. Browser: Firefox 111.0.1

Kalgan answered 31/3, 2023 at 15:43 Comment(0)
K
7

A one-liner to iteratively remove all the children of a node from the DOM

Array.from(node.children).forEach(c => c.remove())

Or

[...node.children].forEach(c => c.remove())
Killian answered 22/12, 2022 at 9:4 Comment(0)
B
6

Here is what I usually do :

HTMLElement.prototype.empty = function() {
    while (this.firstChild) {
        this.removeChild(this.firstChild);
    }
}

And voila, later on you can empty any dom element with :

anyDom.empty()
Broadloom answered 9/9, 2018 at 20:27 Comment(2)
I like this solution! Any reason I should use this over setting innerHTML to a blank string?Orvieto
performance : domEl.innerHTML = "" is poor and considered bad practiceBroadloom
W
5

In response to DanMan, Maarten and Matt. Cloning a node, to set the text is indeed a viable way in my results.

// @param {node} node
// @return {node} empty node
function removeAllChildrenFromNode (node) {
  var shell;
  // do not copy the contents
  shell = node.cloneNode(false);

  if (node.parentNode) {
    node.parentNode.replaceChild(shell, node);
  }

  return shell;
}

// use as such
var myNode = document.getElementById('foo');
myNode = removeAllChildrenFromNode( myNode );

Also this works for nodes not in the dom which return null when trying to access the parentNode. In addition, if you need to be safe a node is empty before adding content this is really helpful. Consider the use case underneath.

// @param {node} node
// @param {string|html} content
// @return {node} node with content only
function refreshContent (node, content) {
  var shell;
  // do not copy the contents
  shell = node.cloneNode(false);

  // use innerHTML or you preffered method
  // depending on what you need
  shell.innerHTML( content );

  if (node.parentNode) {
    node.parentNode.replaceChild(shell, node);
  }

  return shell;
}

// use as such
var myNode = document.getElementById('foo');
myNode = refreshContent( myNode );

I find this method very useful when replacing a string inside an element, if you are not sure what the node will contain, instead of worrying how to clean up the mess, start out fresh.

Weasel answered 15/3, 2013 at 20:40 Comment(1)
the worst thing ever. if you are replacing the original node with its clone, you are losing the reference to the original node. none of the event handlers and other bindings won't work.Afield
P
5

Using a range loop feels the most natural to me:

for (var child of node.childNodes) {
    child.remove();
}

According to my measurements in Chrome and Firefox, it is about 1.3x slower. In normal circumstances, this will perhaps not matter.

Painterly answered 6/12, 2018 at 20:3 Comment(0)
I
4
var empty_element = function (element) {

    var node = element;

    while (element.hasChildNodes()) {              // selected elem has children

        if (node.hasChildNodes()) {                // current node has children
            node = node.lastChild;                 // set current node to child
        }
        else {                                     // last child found
            console.log(node.nodeName);
            node = node.parentNode;                // set node to parent
            node.removeChild(node.lastChild);      // remove last node
        }
    }
}

This will remove all nodes within the element.

Incurrent answered 1/2, 2014 at 13:46 Comment(1)
...because it's unnecessary complex, and no explanation is given as to how it works (which is actually non-obvious), I suspect.Sialoid
P
4

Simplest way of removing the child nodes of a node via Javascript

var myNode = document.getElementById("foo");
while(myNode.hasChildNodes())
{
   myNode.removeChild(myNode.lastChild);
}
Peroneus answered 18/7, 2016 at 18:12 Comment(0)
V
4

There are couple of options to achieve that:

The fastest ():

while (node.lastChild) {
  node.removeChild(node.lastChild);
}

Alternatives (slower):

while (node.firstChild) {
  node.removeChild(node.firstChild);
}

while (node.hasChildNodes()) {
  node.removeChild(node.lastChild);
}

Benchmark with the suggested options

Visitant answered 27/1, 2017 at 13:49 Comment(0)
A
4

element.innerHTML = "" (or .textContent) is by far the fastest solution

Most of the answers here are based on flawed tests

For example: https://jsperf.com/innerhtml-vs-removechild/15
This test does not add new children to the element between each iteration. The first iteration will remove the element's contents, and every other iteration will then do nothing. In this case, while (box.lastChild) box.removeChild(box.lastChild) was faster because box.lastChild was null 99% of the time

Here is a proper test: https://jsperf.com/innerhtml-conspiracy

Finally, do not use node.parentNode.replaceChild(node.cloneNode(false), node). This will replace the node with a copy of itself without its children. However, this does not preserve event listeners and breaks any other references to the node.

Accroach answered 5/8, 2020 at 19:38 Comment(0)
I
3

innerText is the winner! http://jsperf.com/innerhtml-vs-removechild/133. At all previous tests inner dom of parent node were deleted at first iteration and then innerHTML or removeChild where applied to empty div.

Integrity answered 27/1, 2014 at 11:8 Comment(2)
innerText is a proprietary MS thing though. Just saying.Relativistic
Pretty sure this is a flawed test - it relies on box being available not as a var but through DOM lookup based on id, and since the while loop makes this slow call many times it's penalized.Ldopa
S
3

Why aren't we following the simplest method here "remove" looped inside while.

const foo = document.querySelector(".foo");
while (foo.firstChild) {
  foo.firstChild.remove();     
}
  • Selecting the parent div
  • Using "remove" Method inside a While loop for eliminating First child element , until there is none left.
Suppository answered 21/5, 2018 at 9:58 Comment(2)
Please explain your lines of code so other users can understand its functionality. Thanks!Belloir
@IgnacioAra Done!Suppository
B
3
 let el = document.querySelector('#el');
 if (el.hasChildNodes()) {
      el.childNodes.forEach(child => el.removeChild(child));
 }
Blondie answered 25/11, 2019 at 21:26 Comment(0)
D
2

i saw people doing:

while (el.firstNode) {
    el.removeChild(el.firstNode);
}

then someone said using el.lastNode is faster

however I would think that this is the fastest:

var children = el.childNodes;
for (var i=children.length - 1; i>-1; i--) {
    el.removeNode(children[i]);
}

what do you think?

ps: this topic was a life saver for me. my firefox addon got rejected cuz i used innerHTML. Its been a habit for a long time. then i foudn this. and i actually noticed a speed difference. on load the innerhtml took awhile to update, however going by addElement its instant!

Delatorre answered 3/2, 2014 at 10:3 Comment(3)
well i think whether is fastest or not, some jsperf tests can prove either caseDermot
super work thanks for those tests. they dont include the for (var i=0... one though. But here is what i got when i ran those tests: i.imgur.com/Mn61AmI.png so in those three tests firstNode was faster than lastNode and innerHTML which is real coolDelatorre
i added the tests: jsperf.com/innerhtml-vs-removechild/220 interesting stuff doing el.firstNode method is the fastest way it seemsDelatorre
C
2

Best Removal Method for ES6+ Browser (major browsers released after year 2016):

Perhaps there are lots of way to do it, such as Element.replaceChildren(). I would like to show you an effective solution with only one redraw & reflow supporting all ES6+ browsers.

function removeChildren(cssSelector, parentNode){
    var elements = parentNode.querySelectorAll(cssSelector);
    let fragment = document.createDocumentFragment(); 
    fragment.textContent=' ';
    fragment.firstChild.replaceWith(...elements);
}

Usage: removeChildren('.foo',document.body);: remove all elements with className foo in <body>

Comet answered 28/7, 2021 at 19:27 Comment(2)
No need for the textContent just do fragment.replaceChildren(...elements) instead of fragment.firstChild.replaceWith(...elements)Tlemcen
@Danny'365CSI'Engelman replaceChildren is a relatively new DOM method. (e.g. FireFox >=78) while replaceWith can run with Firefox>=49. If your target browsers are the latest versions without considering Waterfox Classic, replaceChildren could be better.Comet
Y
1

Generally, JavaScript uses arrays to reference lists of DOM nodes. So, this will work nicely if you have an interest in doing it through the HTMLElements array. Also, worth noting, because I am using an array reference instead of JavaScript proto's this should work in any browser, including IE.

while(nodeArray.length !== 0) {
  nodeArray[0].parentNode.removeChild(nodeArray[0]);
}
Yusem answered 13/7, 2017 at 21:14 Comment(0)
T
1

Just saw someone mention this question in another and thought I would add a method I didn't see yet:

function clear(el) {
    el.parentNode.replaceChild(el.cloneNode(false), el);
}

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

The clear function is taking the element and using the parent node to replace itself with a copy without it's children. Not much performance gain if the element is sparse but when the element has a bunch of nodes the performance gains are realized.

Tuber answered 14/11, 2018 at 21:26 Comment(2)
Actually it seems it was mentioned here https://mcmap.net/q/45333/-remove-all-child-elements-of-a-dom-node-in-javascriptVito
Felix I must have missed that, thanks for the correction +1.Tuber
G
1

Functional only approach:

const domChildren = (el) => Array.from(el.childNodes)
const domRemove = (el) => el.parentNode.removeChild(el)
const domEmpty = (el) => domChildren(el).map(domRemove)

"childNodes" in domChildren will give a nodeList of the immediate children elements, which is empty when none are found. In order to map over the nodeList, domChildren converts it to array. domEmpty maps a function domRemove over all elements which removes it.

Example usage:

domEmpty(document.body)

removes all children from the body element.

Gingras answered 10/12, 2019 at 10:31 Comment(0)
S
1

You can remove all child elements from a container like below:

function emptyDom(selector){
 const elem = document.querySelector(selector);
 if(elem) elem.innerHTML = "";
}

Now you can call the function and pass the selector like below:

If element has id = foo

emptyDom('#foo');

If element has class = foo

emptyDom('.foo');

if element has tag = <div>

emptyDom('div')
Sanjay answered 11/7, 2020 at 16:32 Comment(0)
S
1

If you want to empty entire parent DOM then it's very simple...

Just use .empty()

function removeAll() {
  $('#parent').empty();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="removeAll()">Remove all the element of parent</button>
<div id="parent">
  <h3>Title</h3>
  <p>Child 1</p>
  <p>Child 2</p>
  <p>Child 3</p>
</div>
Squama answered 22/4, 2021 at 15:20 Comment(0)
J
0

I did it like this

data = {
    "messages": [
        [0, "userName", "message test"],
        [1, "userName1", "message test1"]
    ]
}
for (let i = 0; i < data.messages.length; i++) {
    var messageData = document.createElement('span')
    messageData.className = 'messageClass'
    messageData.innerHTML = `${data.messages[i][2]} ${'<br />'}`
    $(".messages").append(messageData)
}

$('#removeMessages').on('click', () => {
    node = $('.messages').get(0)
    while (node.firstChild) {
        node.firstChild.remove()
    }
    $('#removeMessages').toggle(500)
    $('#addMessages').toggle(500)
})

$('#addMessages').on('click', () => {
    for (let i = 0; i < data.messages.length; i++) {
        var messageData = document.createElement('span')
        messageData.className = 'messageClass'
        messageData.innerHTML = `${data.messages[i][2]} ${'<br />'}`
        $(".messages").append(messageData)
    }
    $('#addMessages').toggle(500)
    $('#removeMessages').toggle(500)
})
#addMessages{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="messages"></div>
<button type='button' id="removeMessages">Remove</button>
<button type='button' id="addMessages">Add MEssages</button>
Jaunitajaunt answered 10/1, 2022 at 16:57 Comment(0)
E
-1

simply only IE:

parentElement.removeNode(true);

true - means to do deep removal - which means that all child are also removed

Encaustic answered 15/12, 2016 at 12:31 Comment(0)
H
-2

Other ways in jQuery

var foo = $("#foo");
foo.children().remove();
//or
$("*", foo ).remove();
//or
foo.html("");
//or
foo.empty();
Houseleek answered 16/10, 2011 at 18:9 Comment(2)
Down-voting because OP said answers in straight DOM are preferred.Bloodmobile
Also, jQuery has .empty() method, just $("#foo").empty() would be enoughDiatessaron
W
-2

simple and fast using for loop!!

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

    for(var i = myNode.childNodes.length - 1; i >= 0; --i) {
      myNode.removeChild(myNode.childNodes[i]);
    }

this will not work in <span> tag!

Wharton answered 18/8, 2018 at 18:30 Comment(1)
in above all solution no code is removing <span> tagWharton
S
-2

An asynchronous, recursive approach, if need be:

document.iterCount=0;
async function removeChildren(cssSelector){
    var parent=document.querySelector(cssSelector);
    if (parent && parent.childElementCount){
        for (var child of parent.children){
            child.remove();
        };
        if (parent.childElementCount > 0){
                document.iterCount++;
                setTimeout(removeChildren(cssSelector), 0.1*1000);
        }
        else {
            console.log(`returned in ${document.iterCount} tries`);
        };

    } else {
        console.info(`there are no children for the element whose selector is '${cssSelector}'`)
        return 0;
    }
}

get rid of document.iterCount when implementing it, it's just there to show that sometimes a single pass at clearing the child nodes will not suffice.

Stackhouse answered 20/4, 2023 at 13:16 Comment(0)
M
-3

If you want to put something back into that div, the innerHTML is probably better.

My example:

<ul><div id="result"></div></ul>

<script>
  function displayHTML(result){
    var movieLink = document.createElement("li");
    var t = document.createTextNode(result.Title);
    movieLink.appendChild(t);
    outputDiv.appendChild(movieLink);
  }
</script>

If I use the .firstChild or .lastChild method the displayHTML() function doesnt work afterwards, but no problem with the .innerHTML method.

Multiple answered 18/10, 2017 at 7:2 Comment(0)
O
-4

This is a pure javascript i am not using jQuery but works in all browser even IE and it is verry simple to understand

   <div id="my_div">
    <p>Paragraph one</p>
    <p>Paragraph two</p>
    <p>Paragraph three</p>
   </div>
   <button id ="my_button>Remove nodes ?</button>

   document.getElementById("my_button").addEventListener("click",function(){

  let parent_node =document.getElemetById("my_div"); //Div which contains paagraphs

  //Let find numbers of child inside the div then remove all
  for(var i =0; i < parent_node.childNodes.length; i++) {
     //To avoid a problem which may happen if there is no childNodes[i] 
     try{
       if(parent_node.childNodes[i]){
         parent_node.removeChild(parent_node.childNodes[i]);
       }
     }catch(e){
     }
  }

})

or you may simpli do this which is a quick way to do

document.getElementById("my_button").addEventListener("click",function(){

 let parent_node =document.getElemetById("my_div");
 parent_node.innerHTML ="";

})
Olgaolguin answered 30/3, 2017 at 6:2 Comment(0)
O
-14

with jQuery :

$("#foo").find("*").remove();
Oblation answered 17/10, 2010 at 20:54 Comment(1)
$('#foo').children().remove() much more logicalMonto

© 2022 - 2024 — McMap. All rights reserved.