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: Cannot read properties of null (reading 'addEventListener')

Posted at

記事概要

JavaScriptによって発生したエラーUncaught TypeError: Cannot read properties of null (reading 'addEventListener')を解消する方法について、まとめる

事象

下記エラーがコンソール上で発生する

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

エラー原因

JavaScriptで定義した要素が存在しないため、要素がnullになってしまう
nullに対してaddEventListenerを使用したことでエラーが発生

JavaScriptを使用しないページで発生する

対応方法

要素がnullの場合、それ以降のコードを読まないようにどちらかを追記

  • return false;
    const priceInput = document.getElementById("item-price");
      if (!priceInput){ return false;} // 追記
      priceInput.addEventListener("input", () => {
        // 中略
      });
    
  • return null;
    const priceInput = document.getElementById("item-price");
      if (!priceInput) return null; // 追記
      priceInput.addEventListener("input", () => {
        // 中略
      });
    
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?