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?
Say I have the following (ugly) HTML:
我如何用JS可以從一個DOM元素內刪除其所有的child元素
如以下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 is left?
Could I just do:
假設我如此設了一個變數我該如何把 foo的children都刪掉?
我可以這樣做嗎?
myNode.childNodes = new Array();
or should I be using some combination of removeElement?
I'd like the answer to be straight up DOM; though extra points if you also provide an answer in jQuery along with the DOM-only answer.
Option 1 (much slower, see comments below):
選項1(比較慢)
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 2 (much faster):
選項2(比較快)
doFoo.onclick = () => {
const myNode = document.getElementById("foo");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
<div id='foo' style="height: 100px; width: 100px; border: 1px solid black;">
<span>Hello</span>
</div>
<button id='doFoo'>Remove Via removeChild</button>