Posted on • Updated on

Cannot read property 'addEventListener' of null



The simplest way to avoid an error Cannot read property 'addEventListener' of null is to check whether the variable is null or not. 

<button id="myButton">Click me</button>
 var btn = document.getElementById('myButton');
  if(btn){ //check if btn exists or not.
   btn.addEventListener('click', myFunction);
 function myFunction(){
   console.log('Hello World');
end of article

Related Posts

Join Our Newsletter

Want the latest & greatest from our blog straight to your inbox with some exclusive offers from our partners and sponsors?

We won't spam. Promise.