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

  • I think the easiest approach would be to just check that el is not null before adding an event listener:

    const el = document.getElementById('overlayBtn');
    if (el) {
      el.addEventListener('click', swapper, false);
    }
    // or, to keep it clean
    el?.addEventListener('click', swapper, false);
    

    You can also wait to run your code until DOMContentLoaded has completed:

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