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で「Uncaught TypeError: ...remove is not a function」が出た時の対処法

1
Posted at

JavaScriptで特定の要素を削除しようとした際、以下のようなエラーに遭遇することがあります。

Uncaught TypeError: toRemoveElement.remove is not a function

1. 発生していた問題のコード

特定のクラス名を持つ要素を取得し、削除しようとしたコードです。

const toRemoveElement = document.getElementsByClassName('mt-3 alert alert-danger');

if(toRemoveElement){
  toRemoveElement.remove();
}

一見正しそうに見えますが、実行するとコンソールに上記のエラーが表示されます。

2. エラーの原因

エラーの理由は、getElementsByClassName が返すデータの型。

期待していたもの: 指定したclassを持つDOM(divタグ)単一のHTML要素

取得できたのは: HTMLCollection(複数の要素が詰まった「配列のような」リスト)

.remove() メソッドは、個別の「要素」に対して実行できる命令。そのため、要素の「リスト」に対して直接実行しようとすると、「そんな関数(命令)は存在しません」というエラーになってしまいます。

3. 解決策:querySelector を使う

最もシンプルで現代的な解決策は、document.querySelector を使うことです。

// クラス名の指定はCSSセレクタと同じ形式(先頭にドット)で記述します
const toRemoveElement = document.querySelector('.mt-3.alert.alert-danger');

// 要素が存在する場合のみ削除を実行
if (toRemoveElement) {
  toRemoveElement.remove();
}

4.おなじみのgetElementByIdを使う

const toRemoveElements = document.getElementsByClassName('mt-3 alert alert-danger');

// リストが空でない(要素が存在する)かチェックして、0番目を削除
if (toRemoveElements.length > 0) {
  toRemoveElements[0].remove();
}

toRemoveElements[0]としなければならないのがちょっとトリッキーです。

4. まとめ

getElementsByClassName は要素のリストを返すため、そのままでは remove() できない。
特定の1つを削除したいなら、最初から単一の要素を返す querySelector を使うのがベスト。

もし複数の要素をすべて消したい場合は、querySelectorAll を使ってループ処理を行う。

DOM操作で「関数がない」と言われたときは、まず「単一の要素を操作しているか、リストを操作しているか」を確認してみましょう!

1
0
0

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?