javascript エラー「Uncaught TypeError: xxx.addEventListener is not a function」の解決方法

javascript エラー「Uncaught TypeError: xxx.addEventListener is not a function」の解決方法

javascriptで、エラー「Uncaught TypeError: xxx.addEventListener is not a function」が発生した場合の原因と解決方法を記述してます。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 103.0.5060.134

エラー内容

以下の、チェックボックスに全てイベントを登録するコードを実行した際に発生。

<input type="checkbox" name="chk" value="a" />
<input type="checkbox" name="chk" value="b" />
<input type="checkbox" name="chk" value="c" />

<script>

let elm = document.getElementsByName("chk");

elm.addEventListener('click', function () {
    console.log(elm[i].value)
});

</script>

エラーメッセージ

Uncaught TypeError: elm.addEventListener is not a function

画像

firefox102の場合は、以下のエラーが発生します。

Uncaught TypeError: elm.addEventListener is not a function

画像

safari15.5では、以下のエラーとなります。

TypeError: elm.addEventListener is not a function. (In 'elm.addEventListener('click', function () {
    console.log(elm[i].value)
})', 'elm.addEventListener' is undefined)

画像

原因

「getElementsByName」の戻り値は、複数要素の「HTMLCollection」なため

解決方法

「for」文を使用して、個別に登録する

<input type="checkbox" name="chk" value="a" />
<input type="checkbox" name="chk" value="b" />
<input type="checkbox" name="chk" value="c" />

<script>

let elm = document.getElementsByName("chk");

elm.addEventListener('click', function () {
    console.log(elm[i].value)
});

</script>

実行結果