Uncaught TypeError: Cannot read property 'addEventListener' of undefined

Created 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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.