はじめに
JavaScriptでN番目の子要素を削除する方法について。
主な方法は2つ。
- 親要素のchildrenプロパティで子要素のDOMを取得して削除
- nth-child使って削除(コメントを参照)
解決方法
単純に1つの子要素を削除する場合。
(nth-childを使う場合でも任意の子要素を削除できます。)
『子要素のN番目』を削除できるので、子要素に何が来るか分からない場合に使うと良い。
またNは0からカウントする。
const delIndex = N; // Nは0以上の整数
const parentNode = document.getElementById('parent');
parentNode.children[delIndex].remove();
コメントより
子要素を指定して削除する場合。
(前述の通り、divの記述をなくせば任意の子要素を削除できます)
『N番目のELE』を指定して削除するので、子要素が確実にELEの場合に使うと良い。
またNは1からカウントする。
const delIndex = N; // Nは自然数(1以上の整数)
// 【不要】const delTag = ELE; // ELEはHTMLタグ名(divなど)
// 【不要】document.querySelector(`#parent ${delTag}:nth-child(${delIndex})`)?.remove();
document.querySelector(`#parent :nth-child(${delIndex})`)?.remove();
拡張
複数の子要素を削除する場合は、こんな感じで使うのも手。
const indexArr = [...]; // 0以上の整数N
indexArr.sort((a,b) => b - a);
const parentNode = document.getElementById('parent');
indexArr.map(i => {
if (parentNode.children.length > i) {
parentNode.children[i].remove();
}
});
参考