0
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')

0
Posted at

はじめに

こういうディレクトリ構成

.
├── index.html
└── main.js

問題

  • document.getElementById('hoge').addEventListener~~ としていた時に発生

解決

  • console.logで出して document.getElementById('hoge') 部分がnullであることを確認
  • htmlでmain.jsを読み込んでいる <script> タグがbodyタグの一番上だった。つまりスクリプトが読み込まれた時点ではDOMに要素が存在しないので、document.getElementByIdしても取得できずnullになっていた
  • bodyタグの最後に読み込み用の <script> タグを移動し取得できたので意図通り動作した

終わりに

こちらを参考にさせて頂きました

0
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
0
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?