Cannot read property 'addEventListener' of null
Solution 1
I think the easiest approach would be to just check that el
is not null before adding an event listener:
var el = document.getElementById('overlayBtn');
if(el){
el.addEventListener('click', swapper, false);
}
Solution 2
It seems that document.getElementById('overlayBtn');
is returning null
because it executes before the DOM fully loads.
If you put this line of code under
window.onload=function(){
-- put your code here
}
then it will run without issue.
Example:
window.onload=function(){
var mb = document.getElementById("b");
mb.addEventListener("click", handler);
mb.addEventListener("click", handler2);
}
function handler() {
$("p").html("<br>" + $("p").text() + "<br>You clicked me-1!<br>");
}
function handler2() {
$("p").html("<br>" + $("p").text() + "<br>You clicked me-2!<br>");
}
Solution 3
I faced a similar situation. This is probably because the script is executed before the page loads. By placing the script at the bottom of the page, I circumvented the problem.
Solution 4
script is loading before body, keep script after body
Solution 5
I was getting the same error, but performing a null check did not seem to help.
The solution I found was to wrap my function inside an event listener for the whole document to check when the DOM finished loading.
document.addEventListener('DOMContentLoaded', function () {
el.addEventListener('click', swapper, false);
});
I think this is because I am using a framework (Angular) that is changing my HTML classes and ID's dynamically.
Related videos on Youtube
Comments
-
morocklo almost 2 years
I have to use vanilla JavaScript for a project. I have a few functions, one of which is a button that opens a menu. It works on pages where the target id exists, but causes an error on pages where the id doesn't exist. On those pages where the function cannot find the id, I receive a "Cannot read property 'addEventListener' of null " error and none of my other functions work.
Below is the code for the button that opens the menu.
function swapper() { toggleClass(document.getElementById('overlay'), 'open'); } var el = document.getElementById('overlayBtn'); el.addEventListener('click', swapper, false); var text = document.getElementById('overlayBtn'); text.onclick = function(){ this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu"; return false; };
How do I deal with this? I probably need to all wrap this code in another function or use an if/else statement so that it only searches for the id on specific pages, but not sure exactly.
-
BlaShadow almost 10 yearscan you show the html code. it seems that can not find element with id 'overlayBtn'
-
Etai almost 10 yearsOn those pages where the function cannot find the id, I receive a "Cannot read property 'addEventListener' of null " error and none of my other functions work. I think the answer was pretty much in the question. You couldn't find the element, so you can't add an event listener to it...
-
Deke about 8 yearsIt can simply happen if you have used
class
in your html instead ofid
and you calling for agetElementById
in your scripts. -
Malakai almost 4 yearsJust faced similar issue where
addEventListener could be null
. Moving<script src="..."></script>
after<body/>
tag seem to solve this issue. -
r3za about 3 years@Reborn I was getting this error for so long. This solved it.
-
Aryan almost 3 yearsBest Approach is moving <script src="..."></script> after <body/>
-
-
morocklo almost 10 yearsawesome. that did the trick. I also moved the onclick function into that if statement. I posted the final code below.
-
rpeg about 8 yearsYeah, I think there are multiple solutions to this problem depending on the scenario.
-
Admin almost 7 yearsit will be
null
before react component did mount! -
Machavity over 6 yearsIncorrect. This is old school thinking. Loading at the end delays the loading, as you stated, but it does not ensure the DOM is fully drawn. I've had older pages that used this hack fail to run because the DOM draw was slower than the load. This answer ensures the DOM is drawn before execution.
-
Machavity over 6 yearsThe drawing of the page can sometimes take longer than the loading of the script does, so the position isn't that important in all cases. Adding a listener is the preferred way, but
load
is also deprecated for the same reason. DOMContentLoaded is the preferred way, since it fires only after the DOM is fully drawn. -
Natalie Jimenez over 6 yearsThanks I will try. I got my answer from Mozilla network. I thought it was a trustful source.
-
VegaStudios about 5 yearsThanks man :D Exactly what I was looking for....I've got multiple listeners in my app, and the listeners are spread out in different views. If the element is present on the page, it was mucking up my JS
-
ennth over 3 years'Doh, I have my JS file called in the <head> , moved to <body> and it worked , your comment helped me thx
-
S_i_l_e_n_t C_o_d_e_r over 3 yearsreally dude you helped me a lot!
-
bachree over 3 yearsI have combined this method with the following stackoverflow.com/a/1760268/5923833 to resolve the issue with this error. In my case the trigger for the error was hitting enter or reload for the page and then changing the tab to another page. Now, with your code and the other solution I was able to prevent the error on page load and then add the event listener when the user comes back to the tab.
-
Vyshak Puthusseri over 3 yearsBut @Machavity, in that answer also, the function is waiting for the DOM to load completely. So what is the difference here. Both answers are right?? Could you please explain.
-
Machavity over 3 years@VyshakPuthusseri They're not quite the same thing. Your browser has to load content, then draw the content (DOM) out. In most cases the browser will finish in the order loaded, but there are times when that's not true, in which case your JS breaks trying to reference unrendered objects. DOMContentLoaded is an event that explicitly lets you wait for the browser to finish drawing the DOM first, rather than crossing your fingers and hoping for the best.
-
Vyshak Puthusseri over 3 yearsOk. Understood my mistake. @Machavity Thanks for that information.
-
Manel about 3 yearsThis code does not respond to the question. If elements are not found (el, el2) then error will show in console.
-
Hammad Khan about 3 yearsCorrect answer.
-
Aryan almost 3 yearsInsted move the <script src="..."></script> after <body/>
-
Olu Ayeni over 2 yearsYou are perfectly right. I added async and the error message stopped
-
trincot over 2 yearsThe accepted answer that was posted in 2014 deals with this.