LoginSignup
11
7

More than 3 years have passed since last update.

addEventListenerを使用する際に注意するべきこと

Posted at

jsの実装中にエラーが起きたのでまとめます。

addEventListnerとは

addEventListenerとは、イベント発火の際に実行する関数を定義するためのメソッドです。

以下のようにして実行できます。


要素.addEventListener('イベント名', 関数);

エラーが起きたときのコード


function calc() {
  const value = document.getElementsByClassName("price-input");
  value.addEventListener('input', (e) => {
    console.log("")
  });
}

window.addEventListener("load", calc);

エラー内容


Uncaught TypeError: value.addEventListener is not a function
    at calc (calculation.js:5)

なぜかvalueが定義されてないことになっています。

valueがちゃんと定義されているか確認します。

function calc() {
  const value = document.getElementsByClassName("price-input");
  console.log("value")
  value.addEventListener('input', (e) => {
    console.log("")
  });
}

window.addEventListener("load", calc);

コンソールを確認します。

HTMLCollection [input#item_price.price-input, item_price: input#item_price.price-input, item[price]: input#item_price.price-input]

なぜかいっぱいある。。。

そうですgetElementsbyClassNameで取得できるのは
HTMLCollectionというオブジェクト
になります。

HTMLCollectionは複数ノードなので
単一ノードのみ指定できるaddEventListnerでは取得することができなかったのですね。

idで取得するように変更してみます。


function calc() {
  const value = document.getElementById("item_price");

  value.addEventListener('input', (e) =>{
    console.log("")
  });
}

window.addEventListener("load", calc);

これでエラーが解決できました。

11
7
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
11
7