Remove all child elements of a DOM node in JavaScript

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

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

提交回复
热议问题