iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 21
0
Modern Web

從Stack Overflow學前端系列 第 21

從StackOverflow上學CODING(21) JS刪除child元素

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.

還是我該用removeElement?
我希望的答案是直接跟DOM相關的,但如果你能提供jQuery的解答我會給更多分

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>

上一篇
從StackOverflow上學CODING(20) JS偵測手機瀏覽器
下一篇
從StackOverflow上學CODING(22) 使input只接收數字類型的輸入
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言