Uncaught TypeError: Cannot read property 'addEventListener' of undefined

Updated at 11-Jan-2021, By samar

Uncaught TypeError: Cannot read property 'addEventListener' of undefined

With this article, we will examine several different instances of how to solve the "Uncaught TypeError: Cannot read property 'addEventListener' of undefined".

  • <script> 
    var el = document.getElementById('overlayBtn');
    if(el){
      el.addEventListener('click', swapper, false);
    } 
    </script>
    

    You can simply check variable (el) before adding an event listener to element. If element exists then it will add a click event to it. 

Back to code snippet queries related javascript