You will find the "Cannot read property addEventListener of null" error in two situations:
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.
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.
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.
<!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.
<!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>
let btn = document.getElementById("submit"); btn.addEventListener('click', (event)=>{ console.log("Button is clicked."); })