【JavaScript】appendChildとremoveChild

  • このエントリーをはてなブックマークに追加

appendChildメソッドとremoveChildメソッドは対になっている。



よくあるappendChildメソッドとremoveChildメソッドの使い方は次の通り。
2つの使い方を書いておく。


// その1
// 追加
document.getElementById(△△△).appendChild(〇〇〇);
// 削除 
〇〇〇.parentNode.removeChild(〇〇〇);
// 削除 別の方法
document.getElementById(△△△).removeChild(〇〇〇);

// その2
// 追加
document.body.appendChild(〇〇〇);
// 削除
〇〇〇.parentNode.removeChild(〇〇〇);

imgタグをappendChildメソッドで追加して、3秒後にremoveChildメソッドで削除する。
【JavaScript】new Image()を使うパターン2|(株)令和情報ファイナンス (note.com)

その3
document.createDocumentFragment()を使用する場合は次のようにappendChildメソッドとremoveChildメソッドを使用する。
【JavaScript】createDocumentFragmentでDOM操作|(株)令和情報ファイナンス (note.com)

他にもあるのかな?document.createDocumentFragment()がいまいち理解できていない。


// その3
const fragment = document.createDocumentFragment();
const section = fragment.appendChild(document.createElement("section"));
// 追加
document.body.appendChild(fragment);
// 削除
section.parentNode.removeChild(section);
  • このエントリーをはてなブックマークに追加

SNSでもご購読できます。

コメントを残す

*