javascript ノード内の全ての子ノードを削除する
- 2021.01.31
- javascript
- javascript

javascriptで、removeChildとfirstChildを使用して、ノード内の全ての子ノードを削除するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
removeChild使い方
removeChildを使用すると、子ノードを削除することが可能です。
1 |
親ノード.removeChild(削除するノード) |
firstChild使い方
ノード内にある初めのノードを取得します。
1 |
ノード.firstChild |
全てのノードを削除
removeChildとfirstChildを、使って、ノード内の初めのノードがなくなるまでwhile文で削除することで、全ての子ノードを削除することが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/* html */ <div id="main"> <p id="one">one</p> <p id="two">two</p> </div> /* javascript */ 'use strict'; const node = document.getElementById("main"); while(node.firstChild){ node.removeChild(node.firstChild); } |
実行結果をみると、全ての子ノードが削除されて表示されることが確認できます。

また、以下のコードを、
1 2 3 4 5 |
const node = document.getElementById("main"); while(node.firstChild){ node.removeChild(node.firstChild); } |
document.getElementByIdの省略して、簡潔に記述することもできます。
1 2 3 |
while(main.firstChild){ main.removeChild(main.firstChild); } |
サンプルコード
以下は、
「ノードを削除」ボタンをクリックして、全ての子ノードを削除するだけの
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> </head> <script> window.onload = () => { add.onclick = () => { while (main.firstChild) { main.removeChild(main.firstChild) } }; } </script> <body> <div class="container mx-auto my-56 w-64 px-4"> <div id="sample" class="flex flex-col justify-center"> <button id="add" class="bg-gradient-to-r from-green-400 to-blue-500 hover:from-pink-500 hover:to-yellow-500 text-white py-2 px-4 rounded-full mb-3 mt-4"> ノードを削除 </button> <div id="main" class="space-y-4"> <span class="block rounded-md text-white font-extrabold text-center bg-green-500 p-6">削除するノード</span> <span class="block rounded-md text-white font-extrabold text-center bg-green-500 p-6">削除するノード</span> <span class="block rounded-md text-white font-extrabold text-center bg-green-500 p-6">削除するノード</span> </div> </div> </div> </body> </html> |
子ノードが全て削除されていることが確認できます。

-
前の記事
python フォルダを作成する 2021.01.29
-
次の記事
PostgreSQL テーブルのカラムの数をカウントする 2021.01.31
コメントを書く