javascriptfunctiongetelementbyidaddeventlistener

Cannot read property 'addEventListener' of null


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.


Solution

  • The easiest approach would be to check that el is not null before adding your event listener:

    const el = document.querySelector('#overlayBtn');
    if (el) {
      el.addEventListener('click', swapper, false);
    }
    

    This can be also be accomplished with optional chaining

    document.querySelector('#overlayBtn')?.addEventListener('click', swapper, false);
    _____________________________________^
    

    It's important that you wait to run your code until DOMContentLoaded has completed:

    window.addEventListener("DOMContentLoaded", (event) => {
      const el = document.querySelector('#overlayBtn');
      el?.addEventListener('click', swapper, false);
    });