Remove all child elements of a DOM node in JavaScript

前端 未结 30 1385
花落未央
花落未央 2020-11-22 03:28

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

Say I have the following (ugly) HTML:

&

相关标签:
30条回答
  • 2020-11-22 03:55

    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.

    0 讨论(0)
  • 2020-11-22 03:56

    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

    0 讨论(0)
  • 2020-11-22 03:56

    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.

    0 讨论(0)
  • 2020-11-22 03:57

    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.

    0 讨论(0)
  • 2020-11-22 03:58

    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]);
    }
    
    0 讨论(0)
  • 2020-11-22 04:00

    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 - 96% Jun 2020

    0 讨论(0)
提交回复
热议问题