Fixing “Cannot read property ‘addEventListener’ of null” Error in JavaScript
JavaScript is a client-side scripting language that adds interactivity to our websites/web apps. JavaScript allows us to create and update our web apps’ contents dynamically. If you are a JavaScript developer then I am pretty sure that you might regularly use the addEventListener()
method of JavaScript in your projects. In this article, we will be discussing in detail why the “Cannot read property ‘addEventListener’ of null” is encountered and different ways to fix it.
What is addEventListener() in JavaScript?
As discussed above JavaScript is used to add interactivity to web pages and interactivity basically revolves around the events happening on a web page. Events in simple language can be understood as the interactivity of the user with the web pages. The various types of events in JavaScript are onclick
, onchange
, onmouseover
, onmouseout
, etc.
addEventListener()
is a JavaScript inbuilt function that takes three arguments. First is the event that is to be monitored, the second is the function that needs to be executed when the event is triggered and third is the useCapture. Out of these three arguments, only the first two parameters (i.e event & function) are mostly used.
Syntax:
targetedElement.addEventListener(event, function);
Code language: PHP (php)
Why Does This Error Occur?
The main reason why this error occurs in JavaScript is that you are trying to access the method addEventListner()
on such an element that is either not present or cannot be found in the Document Object Model (DOM).
The two reasons for this are:
- Calling the
addEventListener()
method on an element that is either not present or could not be found because of some typo or using an incorrect method in your Document Object Model. - Using the script tag declaration containing the JavaScript code before the declaration of the DOM element on which you are calling the addEventListener() method.
How to Fix This Error?
Now that we know why this error occurs let us see how to fix/handle this error for both cases.
Case 1: Calling addEventListener() on an element not present in DOM
When we try to call the method addEventListener()
on an element that is not present in the Document Object Model (DOM) then this method returns null thus resulting in the above-mentioned error.
Are you using the correct selectors?
The foremost step to fix this error could be to check whether you selected the desired element correctly or not. To ensure this you can make sure that you are using the right selector with the right symbol to target the element like using the ‘#‘ symbol with selectors like getElementByID()
or using the ‘.‘ symbol with selectors like getElementByClassName()
. Also, make sure that you select the right class/id name with the correct spelling.
Checking for null
Make sure that the element that you are targeting through the addEventListener()
method is not null
. You can also check this condition using the if
statement in JavaScript.
Let us consider a code example in which we will target an anchor tag that is not present.
Code Demonstration:
const myLink = document.querySelector("#no_link");
// there is no anchor tag in our HTML file with id "no_link"
if (myLink) {
myLink.addEventListener('click', () => {
console.log('You visited the link');
});
}
Code language: JavaScript (javascript)
In the above code example, we targeted an anchor tag that was not present in the DOM. Here we used a if
condition to check whether the targeted element (anchor tag) exists or not before using the addEventListener()
method. As the ancchor tag is not present therefore we’ll get null
. Since null
is a false value therefore the if
block didn’t get executed.
We could have also used the optional chaining operator represented as ”?.
” in JavaScript.
Code Demonstration:
const myLink = document.querySelector("#no_link");
// there is no anchor tag in our HTML file with id "no_link"
myLink?.addEventListener('click', () => {
console.log('You visited the link')
});
Code language: JavaScript (javascript)
This operator returns undefined if the value of the object is either null or undefined.
Case 2: Position of Script Tag
This error could also occur due to the wrong placement of the script tag containing the JavaScript code.
Placing
The script tag should always be placed just before the closing body tag. Developers usually make the mistake of placing the script tag inside the head section due to which the JavaScript file gets loaded first and then the content inside the <body>
tag of the HTML file gets loaded as the HTML is loaded from top to bottom. Since in this case, the JavaScript file is loaded first, therefore, JavaScript file won’t be able to find any HTML element.
Code Demonstration:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Codedamn</title>
</head>
<body>
<a id="primary_link" href="#">Visit Link</a>
<script src="./app.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
Now since the JavaScript file is placed just before the closing body tag, it will now have the access to all the HTML elements.
Accessing the element in DOMContentLoaded event listener
This error can also be fixed by using DOMContentLoaded
inside the addEventListener()
method. Now after wrapping all your JavaScript code inside your addEventListener()
having DOMContentLoaded
you can access the element that you want to target from this addEventListener()
block. Now with this method, you can place your script tag anywhere in your HTML file because the DOMContentLoaded
is triggered only once the complete HTML is loaded and the DOM also has been made so it doesn’t matter where we have placed the script tag.
Code Demonstration:
HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Codedamn</title>
<script src="./app.js"></script>
</head>
<body>
<a id="primary_link" href="#">Visit Link</a>
</body>
</html>
Code language: HTML, XML (xml)
JavaScript file
document.addEventListener("DOMContentLoaded", () => {
// your javascript code here
const myLink = document.querySelector("#primary_link");
myLink.addEventListener("click", () => {
console.log("You visited the link");
});
});
Code language: JavaScript (javascript)
Now, on clicking the button we will get the message “You visited the link” in our console.
Conclusion
In this article, we covered what is addEventListener()
in JavaScript in brief and what causes the “cannot read property addEventListener’ of null” error in JavaScript. We also covered various ways to fix this error in JavaScript.
Hope you found this article useful.
Sharing is caring
Did you like what Simran Gangwani wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: