?我可以这样做:还是我应该使用 removeElement 的某种组合?我希望答案是直接的 DOM;如果您还在 jQuery 中提供答案以及仅 DOM 的答案,则可以加分。" />

?我可以这样做:还是我应该使用 removeElement 的某种组合?我希望答案是直接的 DOM;如果您还在 jQuery 中提供答案以及仅 DOM 的答案,则可以加分。">

?我可以这样做:还是我应该使用 removeElement 的某种组合?我希望答案是直接的 DOM;如果您还在 jQuery 中提供答案以及仅 DOM 的答案,则可以加分。" />
ChatGPT解决这个技术问题 Extra ChatGPT

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


F
FZs

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 = ''; }

Hello

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 = ''; }

Hello

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); } }

Hello

Option 2 B: Looping to remove every lastElementChild:

This approach preserves all non-Element (namely #text nodes and ) 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); } }

Hello

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); } }); }

Hello


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."
innerHTML only works if you are only dealing with HTML. If there is e.g. SVG inside only Element removal will work
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.
@micha jsperf.com/innerhtml-vs-removechild/151 using .remove() is even faster.
@vsync 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.
M
Mason Freed

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.


The MDN data has now been corrected, and shows full cross-browser support: caniuse.com/?search=replacechildren
It's a pity @Polaris878 hasn't been around since 2018. This should be the new accepted answer.
This is significantly slower than the other methods mentioned here, at least for me.
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.
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.)
G
Gibolt

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


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/childNodes
Cool shorthand, although less readable: while (parent.firstChild && !parent.firstChild.remove());
A one-liner for when performance isn't a huge deal: [...parent.childNodes].forEach(el => el.remove());
This does not work in Typescript... instead use while (selectElem.firstElementChild) { selectElem.firstElementChild.remove(); }
J
Jakub Kukul

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.


Your jsperf is completely broken. That's not very good evidence.
This is currently the best answer. Everything else in this thread is disinformation (!) Thanks for cleaning up all those bad old tests.
"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.
The jsperf tests are broken here. The test engine reports the following: "Error: Dom nodes not recreated during iterations, test results will be meaningless."
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...
P
PleaseStand

If you use jQuery:

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

If you don't:

var foo = document.getElementById('foo');
while (foo.firstChild) foo.removeChild(foo.firstChild);

u
user113716
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.


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.
Why not just put the firstChild expression directly in the condition of the while loop? while ( myNode.firstChild ) {
while(fc = myNode.firstChild){ myNode.removeChild(fc); }
G
Gabe Halsmer

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.


Same thing without LINT warning: clear: function ( container ) { for ( ; ; ) { var child = container.lastChild; if ( !child ) break; container.removeChild( child ); } }
m
mousetail

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


caniuse.com/?search=replaceChildren Latest version of Chrome and Safari just got it. Give it a couple months. God I love auto-updates.
How much HTML parsing happens on an empty string?
D
DanMan

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.


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.
That won't copy event listeners added using addEventListener.
If you can live with that limitation, it's certainly quick: jsperf.com/innerhtml-vs-removechild/137
M
Marco Balestra

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


N
Nathan K

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();
}

This is interesting but it seems fairly slow compared to other methods: jsperf.com/innerhtml-vs-removechild/256
b
bjb568
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.


A text node is not an element
sorry you're right, it removes indeed all children elements
This won't work in older versions of Internet Explorer.
A
Ado Ren

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()

I like this solution! Any reason I should use this over setting innerHTML to a blank string?
performance : domEl.innerHTML = "" is poor and considered bad practice
j
jeroen

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.


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.
e
emu

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.


m
magiccrafter

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


Y
YakovL
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.


...because it's unnecessary complex, and no explanation is given as to how it works (which is actually non-obvious), I suspect.
A
Alexey

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.


innerText is a proprietary MS thing though. Just saying.
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.
C
Chaitanya Bapat

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

var myNode = document.getElementById("foo");
while(myNode.hasChildNodes())
{
   myNode.removeChild(myNode.lastChild);
}

T
Thomas
 let el = document.querySelector('#el');
 if (el.hasChildNodes()) {
      el.childNodes.forEach(child => el.removeChild(child));
 }

N
Noitidart

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!


well i think whether is fastest or not, some jsperf tests can prove either case
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 cool
i added the tests: jsperf.com/innerhtml-vs-removechild/220 interesting stuff doing el.firstNode method is the fastest way it seems
N
Neelansh Verma

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.


Please explain your lines of code so other users can understand its functionality. Thanks!
@IgnacioAra Done!
r
r00t hkr

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]);
}

H
Harry Chilinguerian

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.


Actually it seems it was mentioned here stackoverflow.com/a/15441725/576767
Felix I must have missed that, thanks for the correction +1.
D
Dolph Roger

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.


1
12Me21

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.


C
Chester Fung

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>


No need for the textContent just do fragment.replaceChildren(...elements) instead of fragment.firstChild.replaceWith(...elements)
@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.
h
harish kumar

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 =

emptyDom('div')

A
AllanRibas

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]} ${'
'}` $(".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]} ${'
'}` $(".messages").append(messageData) } $('#addMessages').toggle(500) $('#removeMessages').toggle(500) }) #addMessages{ display:none; }


M
Maciej Gurban

simply only IE:

parentElement.removeNode(true);

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