hello<..."> hello<..."/> hello<..."> hello<...">

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

JavaScript

小小TomNear

2020-03-10

我将如何删除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答案,则需要加分。

第472篇《在JavaScript中删除DOM节点的所有子元素》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

22个回答
神奇Mandy 2020.03.10

with jQuery :

$("#foo").find("*").remove();
小哥GOItachi 2020.03.10

This is a pure javascript i am not using jQuery but works in all browser even IE and it is verry simple to understand

   <div id="my_div">
    <p>Paragraph one</p>
    <p>Paragraph two</p>
    <p>Paragraph three</p>
   </div>
   <button id ="my_button>Remove nodes ?</button>

   document.getElementById("my_button").addEventListener("click",function(){

  let parent_node =document.getElemetById("my_div"); //Div which contains paagraphs

  //Let find numbers of child inside the div then remove all
  for(var i =0; i < parent_node.childNodes.length; i++) {
     //To avoid a problem which may happen if there is no childNodes[i] 
     try{
       if(parent_node.childNodes[i]){
         parent_node.removeChild(parent_node.childNodes[i]);
       }
     }catch(e){
     }
  }

})

or you may simpli do this which is a quick way to do

document.getElementById("my_button").addEventListener("click",function(){

 let parent_node =document.getElemetById("my_div");
 parent_node.innerHTML ="";

})
NearSamHarry 2020.03.10

If you want to put something back into that div, the innerHTML is probably better.

My example:

<ul><div id="result"></div></ul>

<script>
  function displayHTML(result){
    var movieLink = document.createElement("li");
    var t = document.createTextNode(result.Title);
    movieLink.appendChild(t);
    outputDiv.appendChild(movieLink);
  }
</script>

If I use the .firstChild or .lastChild method the displayHTML() function doesnt work afterwards, but no problem with the .innerHTML method.

达蒙伽罗Tom 2020.03.10

simple and fast using for loop!!

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

    for(var i = myNode.childNodes.length - 1; i >= 0; --i) {
      myNode.removeChild(myNode.childNodes[i]);
    }

this will not work in <span> tag!

Green小宇宙伽罗 2020.03.10

The easiest way:

let container = document.getElementById("containerId");
container.innerHTML = "";
飞云伽罗伽罗 2020.03.10

simply only IE:

parentElement.removeNode(true);

true - means to do deep removal - which means that all child are also removed

阿飞飞云 2020.03.10

Other ways in jQuery

var foo = $("#foo");
foo.children().remove();
or
$("*", foo ).remove();
or
foo.html("");
樱斯丁 2020.03.10

Functional only approach:

const domChildren = (el) => Array.from(el.childNodes)
const domRemove = (el) => el.parentNode.removeChild(el)
const domEmpty = (el) => domChildren(el).map(domRemove)

"childNodes" in domChildren will give a nodeList of the immediate children elements, which is empty when none are found. In order to map over the nodeList, domChildren converts it to array. domEmpty maps a function domRemove over all elements which removes it.

Example usage:

domEmpty(document.body)

removes all children from the body element.

逆天乐 2020.03.10

刚看到有人在另一个地方提到这个问题,以为我会添加一个我还没有看到的方法:

function clear(el) {
    el.parentNode.replaceChild(el.cloneNode(false), el);
}

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

clear函数采用元素并使用父节点将其自身替换为没有子元素的副本。如果元素稀疏,则性能提升不多,但是当元素具有一堆节点时,可以实现性能提升。

Green小宇宙伽罗 2020.03.10

为什么我们不遵循这里最简单的方法“删除”却在里面循环了。

const foo = document.querySelector(".foo");
while (foo.firstChild) {
  foo.firstChild.remove();     
}
  • 选择父div
  • 在While循环内使用“删除”方法消除第一个子元素,直到没有剩余子元素为止。
木心小哥 2020.03.10

通常,JavaScript使用数组来引用DOM节点列表。因此,如果您有兴趣通过HTMLElements数组进行此操作,它将很好地工作。另外,值得注意的是,因为我使用的是数组引用而不是JavaScript原型,所以它可以在包括IE在内的任何浏览器中使用。

while(nodeArray.length !== 0) {
  nodeArray[0].parentNode.removeChild(nodeArray[0]);
}
达蒙西里 2020.03.10

使用范围循环对我来说是最自然的:

for (var child of node.childNodes) {
    child.remove();
}

根据我在Chrome和Firefox中的测量,它慢了1.3倍。在正常情况下,这可能无关紧要。

A小宇宙 2020.03.10

我看到人们在做:

while (el.firstNode) {
    el.removeChild(el.firstNode);
}

然后有人说使用el.lastNode更快

但是我认为这是最快的:

var children = el.childNodes;
for (var i=children.length - 1; i>-1; i--) {
    el.removeNode(children[i]);
}

你怎么看?

ps:这个话题对我来说是个救命稻草。我的Firefox插件被拒绝,因为我使用了innerHTML。长期以来一直是习惯。那我就这样 我实际上注意到了速度差异。在加载时,innerhtml花费了一段时间进行更新,但是通过addElement立即进行!

L 2020.03.10

通过Java脚本删除节点的子节点的最简单方法

var myNode = document.getElementById("foo");
while(myNode.hasChildNodes())
{
   myNode.removeChild(myNode.lastChild);
}
ProGreen 2020.03.10

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

Pro梅 2020.03.10
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
        }
    }
}

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

逆天Stafan 2020.03.10

有两种选择可以实现:

最快的 ():

while (node.lastChild) {
  node.removeChild(node.lastChild);
}

替代方案(较慢):

while (node.firstChild) {
  node.removeChild(node.firstChild);
}

while (node.hasChildNodes()) {
  node.removeChild(node.lastChild);
}

具有建议选项的基准

ProItachi 2020.03.10

这是我通常的工作:

HTMLElement.prototype.empty = function() {
    while (this.firstChild) {
        this.removeChild(this.firstChild);
    }
}

瞧,稍后您可以使用以下命令清空任何dom元素:

anyDom.empty()
猴子Davaid神乐 2020.03.10
element.textContent = '';

就像innerText一样,标准除外。一些removeChild(),但使用起来更容易,并且如果您没有太多要删除的内容,则不会对性能造成太大影响。

NearPro 2020.03.10

如果只想让节点没有子节点,也可以像这样复制它:

var dupNode = document.getElementById("foo").cloneNode(false);

取决于您要实现的目标。

神奇老丝 2020.03.10

最快的...

var removeChilds = function (node) {
    var last;
    while (last = node.lastChild) node.removeChild(last);
};

感谢Andrey Lushnikov提供的jsperf.com链接(很酷的网站!)。

编辑:显然,Chrome在firstChild和lastChild之间没有性能差异。最佳答案显示了一个很好的性能解决方案。

LEY猿 2020.03.10

使用现代Javascript,搭配remove

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

这是在ES5中写入删除节点的新方法。这是香草JS,读得多漂亮比以前的版本。

大多数用户应该拥有现代的浏览器,或者您可以根据需要向下转换。

浏览器支持 -2019年12月95%

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android