Remove all child elements of a DOM node in JavaScript

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

提交回复
热议问题