javascript ノード内の全ての子ノードを削除する
- 作成日 2021.01.31
- 更新日 2022.08.04
- javascript
- javascript

javascriptで、removeChildとfirstChildを使用して、ノード内の全ての子ノードを削除するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 103.0.5060.134
removeChild使い方
まずは、「removeChild」の簡単な使い方です。「removeChild」を使用すると子ノードを指定して削除することができます。
親ノード.removeChild(削除するノード)
使用例
<div id="main">
<p id="one">one</p>
text
<p id="two">two</p>
</div>
<script>
document.getElementById('main').removeChild(document.getElementById('one'))
</script>
実行結果

firstChild使い方
次に「firstChild」を使用すると、ノード内にある初めのノードを取得することができます。
ノード.firstChild
使用例
※改行もノードになるため改行は使用してません。
<div id="main"><p id="one">one</p>text<p id="two">two</p></div>
<script>
console.log(
document.getElementById('main').firstChild
)
</script>
実行結果

全てのノードを削除
「removeChild」と「firstChild」を使って、ノード内の初めのノードがなくなるまでwhile文で削除することで、全ての子ノードを削除することが可能です。
<div id="main">
<p id="one">one</p>
<p id="two">two</p>
</div>
<script>
'use strict';
const node = document.getElementById("main");
while(node.firstChild){
node.removeChild(node.firstChild);
}
</script>
実行結果をみると、全ての子ノードが削除されて表示されることが確認できます。

また、以下のコードを、
const node = document.getElementById("main");
while(node.firstChild){
node.removeChild(node.firstChild);
}
document.getElementByIdの省略して、簡潔に記述することもできます。
while(main.firstChild){
main.removeChild(main.firstChild);
}
サンプルコード
以下は、
「ノードを削除」ボタンをクリックして、全ての子ノードを削除するだけの
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!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
コメントを書く