日本語

Fixing “Cannot read properties of null (reading ‘addEventListener’)” in JavaScript

​​JavaScript​HTML,Troubleshooting

When you try to handle a button click or a form submit, the browser console may show Uncaught TypeError: Cannot read properties of null (reading 'addEventListener'). The cause is that the <script> runs before the HTML elements exist, so document.getElementById returns null. Either put the <script> at the end of <body> or add defer, and the error goes away and the button works.

I reproduced this error in a test environment, confirmed the message shown in the console, and checked that the error disappears with each of four fixes.

Note

The test environment was Chromium 153 (headless) launched with Playwright 1.63.0 and Node.js 22.23.4 on Ubuntu 24.04. I did not open the DevTools window. Instead, I received what the browser sends to the console through the DevTools Protocol and displayed it. On each page, after loading, I clicked the button and checked whether the click handler ran. I did not test Firefox or Safari.

Error caused by a script in the head

The following app.js finds the "Save" button and registers a handler that shows a "saved" message when the button is clicked.

js
const button = document.getElementById("save-button");
button.addEventListener("click", () => {
  document.getElementById("message").textContent = "保存しました";
});
console.log("ボタンの準備ができました");

I loaded this app.js inside the <head> of the HTML.

html
<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>保存ボタン</title>
  <script src="app.js"></script>
</head>
<body>
  <button id="save-button">保存</button>
  <p id="message"></p>
</body>
</html>

When I opened this page in Chromium, the console received the following (I removed the heading my test script added).

text
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at http://127.0.0.1:8124/app.js:2:8

This means "cannot read properties of null (reading 'addEventListener')". The second line of the message, app.js:2:8, shows that execution stopped at line 2, column 8 of app.js, which is the addEventListener part of button.addEventListener.

Because the error stopped the script, the "button is ready" message on line 5 was never printed. Clicking the button did nothing.

The script runs before the element exists

The browser reads HTML from top to bottom. When it reaches a <script> with no async, defer, or type="module", it loads and runs that script right away, before continuing to read the rest of the HTML (MDN note on the script element (English)). In the HTML above, when app.js runs, the parser has not yet reached <button id="save-button">.

document.getElementById returns null when no element with that ID exists. null has no addEventListener method, so reading null.addEventListener throws a TypeError.

I logged the result of getElementById("save-button") from inside the <head> and from the end of <body>, and the results differed.

html
<head>
  <script>
    console.log("head の中:", document.getElementById("save-button"));
  </script>
</head>
<body>
  <button id="save-button">保存</button>
  <p id="message"></p>
  <script>
    console.log("body の最後:", document.getElementById("save-button"));
  </script>
</body>
text
head の中: null
body の最後: button#save-button

Before the button, the result is null. After the button, the element is found.

There are four ways to fix it

Each fix makes the code look up the element after the HTML element has been created. The first three use the same app.js as-is. For the fourth, I used a rewritten app-dcl.js. With every fix, the error disappeared, the "button is ready" message appeared in the console, and clicking the button displayed the saved message.

Move the script to the end of body

Move the <script> out of <head> and place it just before </body>.

diff
   <title>保存ボタン</title>
-  <script src="app.js"></script>
 </head>
 <body>
   <button id="save-button">保存</button>
   <p id="message"></p>
+  <script src="app.js"></script>
 </body>

Add defer to the script

Keep the <script> in <head> and add defer.

diff
-  <script src="app.js"></script>
+  <script defer src="app.js"></script>

A script with defer runs after the HTML has been completely parsed (MDN description of the defer attribute (English)). The file is downloaded in parallel while the HTML is being parsed, and parsing is not paused during the download (MDN section on async and defer (English)).

Use type="module"

If the file is written as an ES module, loading it with type="module" runs it at the same timing as defer. The same MDN page says that module scripts are treated as defer from the start, so adding defer makes no difference.

diff
-  <script src="app.js"></script>
+  <script type="module" src="app.js"></script>

Wait for DOMContentLoaded before looking up the element

If you cannot change the HTML, make the JavaScript wait until the HTML has been fully parsed. DOMContentLoaded is the event that fires when the HTML has been completely parsed (MDN description of the DOMContentLoaded event).

js
document.addEventListener("DOMContentLoaded", () => {
  const button = document.getElementById("save-button");
  button.addEventListener("click", () => {
    document.getElementById("message").textContent = "保存しました";
  });
  console.log("ボタンの準備ができました");
});

When I loaded this app-dcl.js inside <head> without defer, no error appeared. The element is looked up only after the event fires, by which point the button already exists.

Point

For new code, the easy choices are to put the script in <head> with defer, or to use type="module". For a script loaded with src, either one runs it after the elements exist, wherever you write the tag.

defer does not apply to inline scripts

If you write the code directly inside <script> without src, adding defer does not fix it. In the following HTML, I put the same logic as app.js in a <script defer> inside <head>.

html
<head>
  <meta charset="utf-8">
  <title>保存ボタン</title>
  <script defer>
    const button = document.getElementById("save-button");
    button.addEventListener("click", () => {
      document.getElementById("message").textContent = "保存しました";
    });
  </script>
</head>

When I opened it, the same error appeared. The location is line 8 of the whole HTML file (the button.addEventListener line).

text
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at http://127.0.0.1:8124/inline-defer.html:8:12

The MDN description of the defer attribute (English) also states that defer has no effect on a script without src. For inline code, move the script to just before </body>, or put the code inside a function called from a DOMContentLoaded event.

If the error remains after moving the script, check the IDs

Even with the <script> just before </body>, you may still see the same error. This happens when the ID in the HTML does not match the ID that the JavaScript is looking for. In the following example, I changed the button's ID to saveButton, but left app.js looking for save-button.

diff
-  <button id="save-button">保存</button>
+  <button id="saveButton">保存</button>

The <script> was placed just before </body>, yet Cannot read properties of null (reading 'addEventListener') still appeared. The message alone cannot tell you whether the cause is timing or a mismatched ID. As the getElementById description notes, IDs are case-sensitive. Compare the IDs in the HTML and the JavaScript character by character. If you use document.querySelector, it also returns null when no element matches (MDN description of querySelector).

Adding ?. does not make the button work

If you write button?.addEventListener(...) using the optional chaining operator ?., then when button is null, the expression stops there without throwing an error (MDN description of the optional chaining operator). I loaded the script in <head> and only added ?.. The console then showed the "button is ready" message, but clicking the button did not display the saved message.

This only hides the fact that the element is missing. The click handler is never registered. Use ?. only when a page may legitimately lack the element, such as when the same script is shared across pages. If the script runs before the element exists, fix it with one of the four methods above.

​Posted by 86