Cannot read property 'addEventListener' of null

869,026

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.

Share:
869,026

Related videos on Youtube

morocklo
Author by

morocklo

Learning to explore the web

Updated on July 08, 2022

Comments

  • morocklo
    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
      BlaShadow almost 10 years
      can you show the html code. it seems that can not find element with id 'overlayBtn'
    • Etai
      Etai almost 10 years
      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. 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
      Deke about 8 years
      It can simply happen if you have used class in your html instead of id and you calling for a getElementById in your scripts.
    • Malakai
      Malakai almost 4 years
      Just faced similar issue where addEventListener could be null. Moving <script src="..."></script> after <body/> tag seem to solve this issue.
    • r3za
      r3za about 3 years
      @Reborn I was getting this error for so long. This solved it.
    • Aryan
      Aryan almost 3 years
      Best Approach is moving <script src="..."></script> after <body/>
  • morocklo
    morocklo almost 10 years
    awesome. that did the trick. I also moved the onclick function into that if statement. I posted the final code below.
  • rpeg
    rpeg about 8 years
    Yeah, I think there are multiple solutions to this problem depending on the scenario.
  • Admin
    Admin almost 7 years
    it will be null before react component did mount!
  • Machavity
    Machavity over 6 years
    Incorrect. 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
    Machavity over 6 years
    The 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
    Natalie Jimenez over 6 years
    Thanks I will try. I got my answer from Mozilla network. I thought it was a trustful source.
  • VegaStudios
    VegaStudios about 5 years
    Thanks 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
    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
    S_i_l_e_n_t C_o_d_e_r over 3 years
    really dude you helped me a lot!
  • bachree
    bachree over 3 years
    I 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
    Vyshak Puthusseri over 3 years
    But @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
    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
    Vyshak Puthusseri over 3 years
    Ok. Understood my mistake. @Machavity Thanks for that information.
  • Manel
    Manel about 3 years
    This code does not respond to the question. If elements are not found (el, el2) then error will show in console.
  • Hammad Khan
    Hammad Khan about 3 years
    Correct answer.
  • Aryan
    Aryan almost 3 years
    Insted move the <script src="..."></script> after <body/>
  • Olu Ayeni
    Olu Ayeni over 2 years
    You are perfectly right. I added async and the error message stopped
  • trincot
    trincot over 2 years
    The accepted answer that was posted in 2014 deals with this.