简体   繁体   English

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

[英]Remove all child elements of a DOM node in JavaScript

How would I go about removing all of the child elements of a DOM node in JavaScript?我将如何着手删除 JavaScript 中 DOM 节点的所有子元素?

Say I have the following (ugly) HTML:假设我有以下(丑陋的)HTML:

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

And I grab the node I want like so:然后我像这样抓住我想要的节点:

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

How could I remove the children of foo so that just <p id="foo"></p> is left?我怎样才能删除foo的孩子,以便只剩下<p id="foo"></p>

Could I just do:我可以这样做吗:

myNode.childNodes = new Array();

or should I be using some combination of removeElement ?还是我应该使用removeElement的某种组合?

I'd like the answer to be straight up DOM;我希望答案是直截了当的 DOM; though extra points if you also provide an answer in jQuery along with the DOM-only answer.如果您还提供了 jQuery 中的答案以及仅 DOM 的答案,则可以加分。

Option 1 A: Clearing innerHTML .选项 1 A:清除innerHTML

  • This approach is simple, but might not be suitable for high-performance applications because it invokes the browser's HTML parser (though browsers may optimize for the case where the value is an empty string).这种方法很简单,但可能不适合高性能应用程序,因为它会调用浏览器的 HTML 解析器(尽管浏览器可能会针对值为空字符串的情况进行优化)。

 doFoo.onclick = () => { const myNode = document.getElementById("foo"); myNode.innerHTML = ''; }
 <div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"> <span>Hello</span> </div> <button id='doFoo'>Remove via innerHTML</button>

Option 1 B: Clearing textContent选项 1 B:清除textContent

  • As above, but use .textContent .如上所述,但使用.textContent According to MDN this will be faster than innerHTML as browsers won't invoke their HTML parsers and will instead immediately replace all children of the element with a single #text node. 根据 MDN,这将比innerHTML更快,因为浏览器不会调用它们的 HTML 解析器,而是会立即将元素的所有子元素替换为单个#text节点。

 doFoo.onclick = () => { const myNode = document.getElementById("foo"); myNode.textContent = ''; }
 <div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"> <span>Hello</span> </div> <button id='doFoo'>Remove via textContent</button>

Option 2 A: Looping to remove every lastChild :选项 2 A:循环删除每个lastChild

  • An earlier edit to this answer used firstChild , but this is updated to use lastChild as in computer-science, in general , it's significantly faster to remove the last element of a collection than it is to remove the first element (depending on how the collection is implemented).对此答案的较早编辑使用firstChild ,但已更新为在计算机科学中使用lastChild通常,删除集合的最后一个元素比删除第一个元素要快得多(取决于集合的方式已实施)。
  • The loop continues to check for firstChild just in case it's faster to check for firstChild than lastChild (eg if the element list is implemented as a directed linked-list by the UA).循环继续检查firstChild以防万一检查firstChild比检查lastChild (例如,如果元素列表被 UA 实现为有向链表)。

 doFoo.onclick = () => { const myNode = document.getElementById("foo"); while (myNode.firstChild) { myNode.removeChild(myNode.lastChild); } }
 <div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"> <span>Hello</span> </div> <button id='doFoo'>Remove via lastChild-loop</button>

Option 2 B: Looping to remove every lastElementChild :选项 2 B:循环删除每个lastElementChild

  • This approach preserves all non- Element (namely #text nodes and <!-- comments --> ) children of the parent (but not their descendants) - and this may be desirable in your application (eg some templating systems that use inline HTML comments to store template instructions).这种方法保留了所有非Element (即#text节点和<!-- comments --> )的父级(但不是它们的后代)的子级 - 这在您的应用程序中可能是可取的(例如,一些使用内联 HTML 的模板系统用于存储模板说明的注释)。
  • This approach wasn't used until recent years as Internet Explorer only added support for lastElementChild in IE9.这种方法直到最近几年才被使用,因为 Internet Explorer 仅在 IE9 中添加了对lastElementChild的支持。

 doFoo.onclick = () => { const myNode = document.getElementById("foo"); while (myNode.lastElementChild) { myNode.removeChild(myNode.lastElementChild); } }
 <div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"> <!-- This comment won't be removed --> <span>Hello <!-- This comment WILL be removed --></span> <!-- But this one won't. --> </div> <button id='doFoo'>Remove via lastElementChild-loop</button>

Bonus: Element.clearChildren monkey-patch:奖励: Element.clearChildren猴子补丁:

  • We can add a new method-property to the Element prototype in JavaScript to simplify invoking it to just el.clearChildren() (where el is any HTML element object).我们可以在 JavaScript 中向Element原型添加一个新的方法属性,以简化对它的调用,只需el.clearChildren() (其中el任何HTML 元素对象)。
  • (Strictly speaking this is a monkey-patch, not a polyfill, as this is not a standard DOM feature or missing feature. Note that monkey-patching is rightfully discouraged in many situations.) (严格来说,这是一个猴子补丁,而不是 polyfill,因为这不是标准的 DOM 功能或缺失的功能。请注意,在许多情况下不鼓励使用猴子补丁。)

 if( typeof Element.prototype.clearChildren === 'undefined' ) { Object.defineProperty(Element.prototype, 'clearChildren', { configurable: true, enumerable: false, value: function() { while(this.firstChild) this.removeChild(this.lastChild); } }); }
 <div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"> <span>Hello <!-- This comment WILL be removed --></span> </div> <button onclick="this.previousElementSibling.clearChildren()">Remove via monkey-patch</button>

In 2022+, use the replaceChildren() API!在 2022+ 年,使用replaceChildren() API!

Replacing all children can now be done with the (cross-browser supported) replaceChildren API :现在可以使用(支持跨浏览器的) replaceChildren API替换所有子项:

container.replaceChildren(...arrayOfNewChildren);

This will do both:这将同时做到:

  • remove all existing children, and删除所有现有的孩子,和
  • append all of the given new children, in one operation.在一次操作中附加所有给定的新子代。

You can also use this same API to just remove existing children, without replacing them:您还可以使用相同的 API 来删除现有的子项,而不替换它们:

container.replaceChildren();

This is fully supported in Chrome/Edge 86+, Firefox 78+, and Safari 14+. Chrome/Edge 86+、Firefox 78+ 和 Safari 14+ 完全支持此功能。 It is fully specified behavior.这是完全指定的行为。 This is likely to be faster than any other proposed method here, since the removal of old children and addition of new children is done without requiring innerHTML , and in one step instead of multiple.这可能比这里提出的任何其他方法都要,因为删除旧子项和添加新子项是在不需要innerHTML的情况下完成的,并且是一步而不是多个。

Use modern Javascript, with remove !使用现代 Javascript,带有remove

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

This is a newer way to write node removal in ES5.这是在 ES5 中编写节点删除的新方法。 It is vanilla JS and reads much nicer than relying on parent.它是普通的 JS,比依赖父级读起来好得多。

All modern browsers are supported.支持所有现代浏览器。

Browser Support - 97% Jun '21浏览器支持- 97% 21 年 6 月

The currently accepted answer is wrong about innerHTML being slower (at least in IE and Chrome), as m93a correctly mentioned.正如 m93a 正确提到的那样,当前接受的关于innerHTML速度较慢的答案是错误的(至少在 IE 和 Chrome 中)。

Chrome and FF are dramatically faster using this method (which will destroy attached jquery data):使用这种方法(这将破坏附加的 jquery 数据),Chrome 和 FF 的速度要快得多:

var cNode = node.cloneNode(false);
node.parentNode.replaceChild(cNode, node);

in a distant second for FF and Chrome, and fastest in IE:在 FF 和 Chrome 中遥遥领先,在 IE 中最快:

node.innerHTML = '';

InnerHTML won't destroy your event handlers or break jquery references , it's also recommended as a solution here: https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML . InnerHTML不会破坏您的事件处理程序或破坏 jquery 引用,它也被推荐为这里的解决方案: https ://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML。

The fastest DOM manipulation method (still slower than the previous two) is the Range removal, but ranges aren't supported until IE9.最快的 DOM 操作方法(仍然比前两种慢)是 Range 删除,但在 IE9 之前不支持范围。

var range = document.createRange();
range.selectNodeContents(node);
range.deleteContents();

The other methods mentioned seem to be comparable, but a lot slower than innerHTML, except for the outlier, jquery (1.1.1 and 3.1.1), which is considerably slower than anything else:提到的其他方法似乎是可比的,但比 innerHTML 慢很多,除了异常值 jquery(1.1.1 和 3.1.1),它比其他任何方法都慢得多:

$(node).empty();

Evidence here:这里的证据:

http://jsperf.com/innerhtml-vs-removechild/167 http://jsperf.com/innerhtml-vs-removechild/300 https://jsperf.com/remove-all-child-elements-of-a-dom-node-in-javascript (New url for jsperf reboot because editing the old url isn't working) http://jsperf.com/innerhtml-vs-removechild/167 http://jsperf.com/innerhtml-vs-removechild/300 https://jsperf.com/remove-all-child-elements-of-a- dom-node-in-javascript (jsperf 重新启动的新 url,因为编辑旧 url 不起作用)

Jsperf's "per-test-loop" often gets understood as "per-iteration", and only the first iteration has nodes to remove so the results are meaningless, at time of posting there were tests in this thread set up incorrectly. Jsperf 的“per-test-loop”通常被理解为“per-iteration”,只有第一次迭代有节点要删除,所以结果没有意义,在发布时,这个线程中的测试设置不正确。

If you use jQuery:如果你使用 jQuery:

$('#foo').empty();

If you don't:如果您不这样做:

var foo = document.getElementById('foo');
while (foo.firstChild) foo.removeChild(foo.firstChild);
var myNode = document.getElementById("foo");
var fc = myNode.firstChild;

while( fc ) {
    myNode.removeChild( fc );
    fc = myNode.firstChild;
}

If there's any chance that you have jQuery affected descendants, then you must use some method that will clean up jQuery data.如果您有任何可能影响 jQuery 的后代,那么您必须使用某种方法来清理 jQuery 数据。

$('#foo').empty();

The jQuery .empty() method will ensure that any data that jQuery associated with elements being removed will be cleaned up. jQuery .empty()方法将确保 jQuery 与被删除元素关联的任何数据都将被清除。

If you simply use DOM methods of removing the children, that data will remain.如果您只是使用DOM方法删除子项,则该数据将保留。

The fastest...最快的...

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

Thanks to Andrey Lushnikov for his link to jsperf.com (cool site!).感谢 Andrey Lushnikov 链接到 jsperf.com (很酷的网站!)。

EDIT: to be clear, there is no performance difference in Chrome between firstChild and lastChild.编辑:需要明确的是,在 Chrome 中 firstChild 和 lastChild 之间没有性能差异。 The top answer shows a good solution for performance.最佳答案显示了一个很好的性能解决方案。

Use elm.replaceChildren() .使用elm.replaceChildren()

It's experimental without wide support, but when executed with no params will do what you're asking for, and it's more efficient than looping through each child and removing it.它在没有广泛支持的情况下是实验性的,但是在没有参数的情况下执行时会满足您的要求,并且比遍历每个子节点并删除它更有效。 As mentioned already, replacing innerHTML with an empty string will require HTML parsing on the browser's part.如前所述,用空字符串替换innerHTML将需要浏览器进行 HTML 解析。

MDN Documentation . MDN 文档

Update It's widely supported now更新它现在被广泛支持

If you only want to have the node without its children you could also make a copy of it like this:如果您只想拥有没有子节点的节点,您也可以像这样复制它:

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

Depends on what you're trying to achieve.取决于您要达到的目标。

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

Ecma6 makes it easy and compact Ecma6 让它变得简单而紧凑

myNode.querySelectorAll('*').forEach( n => n.remove() );

This answers the question, and removes “all child nodes” .这回答了问题,并删除了“所有子节点”

If there are text nodes belonging to myNode they can't be selected with CSS selectors, in this case we've to apply (also):如果存在属于myNode的文本节点,则无法使用 CSS 选择器选择它们,在这种情况下,我们必须应用(也):

myNode.textContent = '';

Actually the last one could be the fastest and more effective/efficient solution.实际上最后一个可能是最快和更有效/高效的解决方案。

.textContent is more efficient than .innerText and .innerHTML , see: MDN .textContent.innerText.innerHTML更有效,参见: MDN

element.textContent = '';

It's like innerText, except standard.就像innerText,除了标准。 It's a bit slower than removeChild() , but it's easier to use and won't make much of a performance difference if you don't have too much stuff to delete.它比removeChild()一点,但它更容易使用,如果你没有太多要删除的东西,它不会对性能产生太大影响。

Here is what I usually do :这是我通常做的:

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

And voila, later on you can empty any dom element with :瞧,稍后您可以使用以下命令清空任何 dom 元素:

anyDom.empty()

In response to DanMan, Maarten and Matt.回应 DanMan、Maarten 和 Matt。 Cloning a node, to set the text is indeed a viable way in my results.克隆一个节点,设置文本在我的结果中确实是一种可行的方式。

// @param {node} node
// @return {node} empty node
function removeAllChildrenFromNode (node) {
  var shell;
  // do not copy the contents
  shell = node.cloneNode(false);

  if (node.parentNode) {
    node.parentNode.replaceChild(shell, node);
  }

  return shell;
}

// use as such
var myNode = document.getElementById('foo');
myNode = removeAllChildrenFromNode( myNode );

Also this works for nodes not in the dom which return null when trying to access the parentNode.这也适用于尝试访问 parentNode 时返回 null 的不在 dom 中的节点。 In addition, if you need to be safe a node is empty before adding content this is really helpful.此外,如果您需要确保在添加内容之前节点为空,这确实很有帮助。 Consider the use case underneath.考虑下面的用例。

// @param {node} node
// @param {string|html} content
// @return {node} node with content only
function refreshContent (node, content) {
  var shell;
  // do not copy the contents
  shell = node.cloneNode(false);

  // use innerHTML or you preffered method
  // depending on what you need
  shell.innerHTML( content );

  if (node.parentNode) {
    node.parentNode.replaceChild(shell, node);
  }

  return shell;
}

// use as such
var myNode = document.getElementById('foo');
myNode = refreshContent( myNode );

I find this method very useful when replacing a string inside an element, if you are not sure what the node will contain, instead of worrying how to clean up the mess, start out fresh.我发现这种方法在替换元素内的字符串时非常有用,如果您不确定节点将包含什么,而不是担心如何清理混乱,重新开始。

Using a range loop feels the most natural to me:使用范围循环对我来说是最自然的:

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

According to my measurements in Chrome and Firefox, it is about 1.3x slower.根据我在 Chrome 和 Firefox 中的测量,它慢了大约 1.3 倍。 In normal circumstances, this will perhaps not matter.在正常情况下,这可能无关紧要。

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.这将删除元素内的所有节点。

There are couple of options to achieve that:有几种选择可以实现这一目标:

The fastest ():最快的 ():

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

Alternatives (slower):替代品(较慢):

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

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

Benchmark with the suggested options使用建议的选项进行基准测试

innerText is the winner! innerText 是赢家! http://jsperf.com/innerhtml-vs-removechild/133 . http://jsperf.com/innerhtml-vs-removechild/133 At all previous tests inner dom of parent node were deleted at first iteration and then innerHTML or removeChild where applied to empty div.在所有先前的测试中,父节点的内部 dom 在第一次迭代时被删除,然后将 innerHTML 或 removeChild 应用于空 div。

Simplest way of removing the child nodes of a node via Javascript通过Javascript删除节点的子节点的最简单方法

var myNode = document.getElementById("foo");
while(myNode.hasChildNodes())
{
   myNode.removeChild(myNode.lastChild);
}
 let el = document.querySelector('#el');
 if (el.hasChildNodes()) {
      el.childNodes.forEach(child => el.removeChild(child));
 }

i saw people doing:我看到人们在做:

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

then someone said using el.lastNode is faster然后有人说使用el.lastNode更快

however I would think that this is the fastest:但是我认为这是最快的:

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

what do you think?你怎么看?

ps: this topic was a life saver for me. ps:这个话题对我来说是救命稻草。 my firefox addon got rejected cuz i used innerHTML.我的 Firefox 插件被拒绝了,因为我使用了 innerHTML。 Its been a habit for a long time.很长一段时间以来都是一种习惯。 then i foudn this.然后我发现了这个。 and i actually noticed a speed difference.我实际上注意到了速度差异。 on load the innerhtml took awhile to update, however going by addElement its instant!在加载innerhtml 需要一段时间来更新,但是通过addElement 会立即更新!

Why aren't we following the simplest method here "remove" looped inside while.为什么我们不遵循这里最简单的方法“删除”在while中循环。

const foo = document.querySelector(".foo");
while (foo.firstChild) {
  foo.firstChild.remove();     
}
  • Selecting the parent div选择父 div
  • Using "remove" Method inside a While loop for eliminating First child element , until there is none left.在 While 循环中使用“删除”方法来消除第一个子元素,直到没有剩余。

Generally, JavaScript uses arrays to reference lists of DOM nodes.通常,JavaScript 使用数组来引用 DOM 节点列表。 So, this will work nicely if you have an interest in doing it through the HTMLElements array.因此,如果您有兴趣通过 HTMLElements 数组进行操作,这将很好地工作。 Also, worth noting, because I am using an array reference instead of JavaScript proto's this should work in any browser, including IE.另外,值得注意的是,因为我使用的是数组引用而不是 JavaScript 原型,所以这应该适用于任何浏览器,包括 IE。

while(nodeArray.length !== 0) {
  nodeArray[0].parentNode.removeChild(nodeArray[0]);
}

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. clear 函数获取元素并使用父节点将自身替换为没有子节点的副本。 Not much performance gain if the element is sparse but when the element has a bunch of nodes the performance gains are realized.如果元素稀疏,性能提升不大,但是当元素有一堆节点时,性能提升就会实现。

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. domChildren 中的“childNodes”将给出直接子元素的 nodeList,当没有找到时,该元素为空。 In order to map over the nodeList, domChildren converts it to array.为了映射 nodeList,domChildren 将其转换为数组。 domEmpty maps a function domRemove over all elements which removes it. domEmpty 将函数 domRemove 映射到删除它的所有元素上。

Example usage:示例用法:

domEmpty(document.body)

removes all children from the body element.从 body 元素中删除所有子元素。

element.innerHTML = "" (or .textContent) is by far the fastest solution element.innerHTML = "" (或 .textContent)是迄今为止最快的解决方案

Most of the answers here are based on flawed tests这里的大多数答案都是基于有缺陷的测试

For example: https://jsperf.com/innerhtml-vs-removechild/15例如: https ://jsperf.com/innerhtml-vs-removechild/15
This test does not add new children to the element between each iteration.此测试不会在每次迭代之间向元素添加新的子元素。 The first iteration will remove the element's contents, and every other iteration will then do nothing.第一次迭代将删除元素的内容,然后其他所有迭代都不会执行任何操作。 In this case, while (box.lastChild) box.removeChild(box.lastChild) was faster because box.lastChild was null 99% of the time在这种情况下, while (box.lastChild) box.removeChild(box.lastChild)更快,因为box.lastChild 99% 的时间都是null

Here is a proper test: https://jsperf.com/innerhtml-conspiracy这是一个适当的测试: https ://jsperf.com/innerhtml-conspiracy

Finally, do not use node.parentNode.replaceChild(node.cloneNode(false), node) .最后,不要使用node.parentNode.replaceChild(node.cloneNode(false), node) This will replace the node with a copy of itself without its children.这将用没有其子节点的自身副本替换节点。 However, this does not preserve event listeners and breaks any other references to the node.但是,这不会保留事件侦听器并破坏对节点的任何其他引用。

Best Removal Method for ES6+ Browser (major browsers released after year 2016): ES6+ 浏览器的最佳移除方法(2016 年后发布的主要浏览器):

Perhaps there are lots of way to do it, such as Element.replaceChildren() .也许有很多方法可以做到这一点,例如Element.replaceChildren() I would like to show you an effective solution with only one redraw & reflow supporting all ES6+ browsers .我想向您展示一个有效的解决方案,它只有一个支持所有 ES6+ 浏览器重绘和重排。

function removeChildren(cssSelector, parentNode){
    var elements = parentNode.querySelectorAll(cssSelector);
    let fragment = document.createDocumentFragment(); 
    fragment.textContent=' ';
    fragment.firstChild.replaceWith(...elements);
}

Usage: removeChildren('.foo',document.body);用法: removeChildren('.foo',document.body); : remove all elements with className foo in <body> : 删除<body>中所有 className foo的元素

You can remove all child elements from a container like below:您可以从容器中删除所有子元素,如下所示:

function emptyDom(selector){
 const elem = document.querySelector(selector);
 if(elem) elem.innerHTML = "";
}

Now you can call the function and pass the selector like below:现在您可以调用该函数并传递选择器,如下所示:

If element has id = foo如果元素有 id = foo

emptyDom('#foo');

If element has class = foo如果元素有 class = foo

emptyDom('.foo');

if element has tag = < div >如果元素有标签 = < div >

emptyDom('div')

If you want to empty entire parent DOM then it's very simple...如果你想清空整个父DOM ,那么这很简单......

Just use .empty()只需使用.empty()

 function removeAll() { $('#parent').empty(); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="removeAll()">Remove all the element of parent</button> <div id="parent"> <h3>Title</h3> <p>Child 1</p> <p>Child 2</p> <p>Child 3</p> </div>

I did it like this我是这样做的

 data = { "messages": [ [0, "userName", "message test"], [1, "userName1", "message test1"] ] } for (let i = 0; i < data.messages.length; i++) { var messageData = document.createElement('span') messageData.className = 'messageClass' messageData.innerHTML = `${data.messages[i][2]} ${'<br />'}` $(".messages").append(messageData) } $('#removeMessages').on('click', () => { node = $('.messages').get(0) while (node.firstChild) { node.firstChild.remove() } $('#removeMessages').toggle(500) $('#addMessages').toggle(500) }) $('#addMessages').on('click', () => { for (let i = 0; i < data.messages.length; i++) { var messageData = document.createElement('span') messageData.className = 'messageClass' messageData.innerHTML = `${data.messages[i][2]} ${'<br />'}` $(".messages").append(messageData) } $('#addMessages').toggle(500) $('#removeMessages').toggle(500) })
 #addMessages{ display:none; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div class="messages"></div> <button type='button' id="removeMessages">Remove</button> <button type='button' id="addMessages">Add MEssages</button>

A one-liner to remove all the children of a node from the DOM从 DOM 中删除节点的所有子node的单行代码

Array.from(node.children).forEach(c => c.remove())

simply only IE:只是IE:

parentElement.removeNode(true);

true - means to do deep removal - which means that all child are also removed true - 表示进行深度移除 - 这意味着所有子项也被移除

How would I go about removing all of the child elements of a DOM node in JavaScript?我将如何在 JavaScript 中删除 DOM 节点的所有子元素?

Say I have the following (ugly) HTML:假设我有以下(丑陋的)HTML:

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

And I grab the node I want like so:我像这样抓住我想要的节点:

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

How could I remove the children of foo so that just <p id="foo"></p> is left?我怎样才能删除foo的孩子,以便只剩下<p id="foo"></p>

Could I just do:我能不能这样做:

myNode.childNodes = new Array();

or should I be using some combination of removeElement ?还是应该使用removeElement某种组合?

I'd like the answer to be straight up DOM;我希望答案是直接的 DOM; though extra points if you also provide an answer in jQuery along with the DOM-only answer.如果您还提供 jQuery 中的答案以及仅 DOM 的答案,则可以加分。

simple and fast using for loop!!使用 for 循环简单快速!!

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!这在<span>标签中不起作用!

Other ways in jQuery jQuery中的其他方式

var foo = $("#foo");
foo.children().remove();
//or
$("*", foo ).remove();
//or
foo.html("");
//or
foo.empty();

If you want to put something back into that div , the innerHTML is probably better.如果您想将某些内容放回该div ,则innerHTML可能会更好。

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.如果我使用.firstChild.lastChild方法,则displayHTML()函数在之后不起作用,但.innerHTML方法没有问题。

This is a pure javascript i am not using jQuery but works in all browser even IE and it is verry simple to understand这是一个纯 javascript,我没有使用 jQuery,但适用于所有浏览器,甚至 IE,而且很容易理解

   <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 ="";

})

用 jQuery :

$("#foo").find("*").remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM