如何在JavaScript中删除DOM节点的所有子元素?

假设我有以下(丑陋的)HTML:

<p id="foo">
    <span>hello</span>
    <div>world</div>
</p>

然后我像这样获取我想要的节点

var myNode = document.getElementById("foo");

我怎么能删除foo的孩子,这样就<p id="foo"></p>是剩下的?

我能不能这样做:

myNode.childNodes = new Array();

或者我应该使用一些组合的removeElement?

我希望答案是直接的DOM;不过,如果你在jQuery中提供了一个dom专用的答案,会有额外的加分。


当前回答

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
        }
    }
}

这将删除元素中的所有节点。

其他回答

innerText是赢家!http://jsperf.com/innerhtml-vs-removechild/133。在所有之前的测试中,父节点的内部dom在第一次迭代时被删除,然后innerHTML或removecchild应用于空div。

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
        }
    }
}

这将删除元素中的所有节点。

element.textContent = '';

它像innerText,除了标准。它比removecchild()稍微慢一点,但更容易使用,如果没有太多东西需要删除,则不会有太大的性能差异。

2022年+,用替代品!

现在可以使用(跨浏览器支持的)replaceChildren API替换所有的子程序:

container.replaceChildren(...arrayOfNewChildren);

这可以做到这两点:

删除所有现有的子节点,和 在一个操作中追加所有给定的新子节点。

你也可以使用相同的API来删除现有的子节点,而不替换它们:

container.replaceChildren();

这在Chrome/Edge 86+, Firefox 78+和Safari 14+中完全支持。它是完全指定的行为。这可能比这里提出的任何其他方法都要快,因为删除旧的子元素和添加新的子元素不需要innerHTML,而且是一步完成的,而不是多个步骤。

为什么我们不在这里使用最简单的方法“remove”循环在while中。

const foo = document.querySelector(".foo");
while (foo.firstChild) {
  foo.firstChild.remove();     
}

选择父div 在While循环中使用“remove”方法消除第一个子元素,直到没有剩余。