1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでN番目の子要素を削除するにはchildrenを使う

Last updated at Posted at 2024-07-13

はじめに

JavaScriptでN番目の子要素を削除する方法について。

主な方法は2つ。

  1. 親要素のchildrenプロパティで子要素のDOMを取得して削除
  2. 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();
  }
});

参考

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?