「JavaScript」removeChildメソッドで複数の要素を削除するサンプル
環境
Windows 10 Home 64bit
Google Chrome 106.0.5249.62
構文
1.変数名 = document.getElementById(セレクター名);
指定要素を取得します
2.複数の要素をループで使用します
for(let i = 変数名.childNodes.length-1; i>=0; i–){
3.複数の要素をループで削除します
変数名.removeChild(変数名.childNodes[i]);
使用例
<!DOCTYPE html>
<html>
<body>
<script>
function delAll(){
//要素tAの取得
const cft = document.getElementById("tA");
// 複数の要素をループする
for(let i = cft.childNodes.length-1; i>=0; i--){
// 複数の要素を削除
cft.removeChild(cft.childNodes[i]);
}
}
</script>
<div id="tA">
<div id="tB">
<p>tokyo</a>
</div>
<div id="tC">
<p>oosaka</a>
</div>
</div>
<input type="button" value="削除" onclick="delAll()">
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
function delAll(){
//要素tAの取得
const cft = document.getElementById("tA");
// 複数の要素をループする
for(let i = cft.childNodes.length-1; i>=0; i--){
// 複数の要素を削除
cft.removeChild(cft.childNodes[i]);
}
}
</script>
<div id="tA">
<div id="tB">
<p>tokyo</a>
</div>
<div id="tC">
<p>oosaka</a>
</div>
</div>
<input type="button" value="削除" onclick="delAll()">
</body>
</html>
<!DOCTYPE html> <html> <body> <script> function delAll(){ //要素tAの取得 const cft = document.getElementById("tA"); // 複数の要素をループする for(let i = cft.childNodes.length-1; i>=0; i--){ // 複数の要素を削除 cft.removeChild(cft.childNodes[i]); } } </script> <div id="tA"> <div id="tB"> <p>tokyo</a> </div> <div id="tC"> <p>oosaka</a> </div> </div> <input type="button" value="削除" onclick="delAll()"> </body> </html>
実行結果
「削除」ボタンを押すと、複数の要素(div要素tBとtC)を削除します