JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

Solve - Cannot read property addEventListener of null in JavaScript

You will find the "Cannot read property addEventListener of null" error in two situations:

  1. You are trying to add an event listener to an HTML element that does not exist in the DOM.
  2. You have inserted the JavaScript code before the HTML, where the desired HTML elements are declared.

Let's understand each situation one by one.

The main reason for getting the error is that when you call the addEventListener() method on an HTML element that is not present in the DOM.

index.js
let btn = document.getElementById("submit-btn");
console.log(btn); //null

btn.addEventListener('click', (event)=>{
  console.log("Button is clicked.");
})

In this example, we tried to access a button whose id "submit-btn" is not present in the DOM because of which the getElementById() method returned null.

To solve the "Cannot read property addEventListener of null" error, check whether the DOM element exists or not before calling the addEventListener() method.

index.html
let btn = document.getElementById("submit-btn");

if(btn){
  btn.addEventListener('click', (event)=>{
    console.log("Button is clicked.");
  })
}else{
  console.log("Button does not exists");
}

If the button does not exist then btn variable is null or undefined. On checking it inside the if statement returns false.

Another situation where you will face the "Cannot read property addEventListener of null" error is when you place the JS script tag before the HTML code.

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <!-- Wrong - JS code before the HTML element -->
  <script src="index.js"></script>

  <button id="submit"></button>
</body>
</html>

In this example, the JavaScript code is inserted before the button element, because of which, the button is not available to the JavaScript code.

To solve the error, make sure that you insert the JS script tag before the closing body element.

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <button id="submit"></button>

  <!-- Right - JS code after the HTML element -->
  <script src="index.js"></script>
</body>
</html>
index.js
let btn = document.getElementById("submit");

btn.addEventListener('click', (event)=>{
  console.log("Button is clicked.");
})

Recommended Posts