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?

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-01-10

自分用メモ
JavaScriptでボタンクリックのイベント発火させようとしたところ、consoleに以下のエラーが出た。

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

ちなみにその時のコードがこちら

index.html
<!doctype html>
<html lang=”ja”>
  <head>
    <title>Index </title>
    <meta charse=”utf8″/>
    <script type="text/javascript" src="{{ url_for('static', filename='index.js') }}"></script>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
  </head>
  <body>
    <div class="input-area">
      <input id="add-text" placeholder="TODOを入力" />
      <button id="add-button">追加</button>
    </div>
  </body>
</html>
index.js
const onClickAdd = () => {
    alert('OK')
}

document
    .getElementById("add-button")   //
    .addEventListner("click", ()=> onClickAdd() );

#原因
原因は、scriptを読み込ませる位置だった模様。
index.htmlが順番に読み込まれていき、id="add-button"のDOMを生成する前に、index.jsが読み込まれid="add-button"に対し、クリックイベントを発火させようとし、DOMが無いのでエラーになるというものだった。

#対策
scriptを読み込ませる位置を一番後ろに持ってくるとでエラー解消した。

index.html
<!doctype html>
<html lang=”ja”>
  <head>
    <title>Index </title>
    <meta charse=”utf8″/>
  </head>
  <body>
    <div class="input-area">
      <input id="add-text" placeholder="TODOを入力" />
      <button id="add-button">追加</button>
    </div>
  </body>
</html>
<script type="text/javascript" src="{{ url_for('static', filename='index.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
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?