Remove all child elements of a DOM node in JavaScript

前端 未结 30 1116
花落未央
花落未央 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: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

提交回复
热议问题