Remove all child elements of a DOM node in JavaScript

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

    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.

提交回复
热议问题