Remove all child elements of a DOM node in JavaScript

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

    var empty_element = function (element) {
    
        var node = element;
    
        while (element.hasChildNodes()) {              // selected elem has children
    
            if (node.hasChildNodes()) {                // current node has children
                node = node.lastChild;                 // set current node to child
            }
            else {                                     // last child found
                console.log(node.nodeName);
                node = node.parentNode;                // set node to parent
                node.removeChild(node.lastChild);      // remove last node
            }
        }
    }
    

    This will remove all nodes within the element.

提交回复
热议问题