Skip to content
Advertisement

Uncaught TypeError: Cannot read property ‘addEventListener’ of null at app.js:2 with checkbox [closed]

I created a checkbox in my html page : <input type="checkbox" class="checkbox" name="checkbox"> And I want to add the class “darkmode” when the checkbox is checked, so I did this in JavaScript :

var checkbox = document.querySelector('intput[name=checkbox]');
checkbox.addEventListener('change',function(){
if(this.checked){
    document.body.classList.add('darkmode');
}
else{
    document.body.classList.remove('darkmode');
}
});

But i get the error :Uncaught TypeError: Cannot read property ‘addEventListener’ of null at app.js:2 Can someone help me ?

Advertisement

Answer

You have a couple of problems.

  • You have a spelling error inptput should be input
  • You should be looking for type=checkbox instead of name=checkbox
  • this.checkbox probably doesn’t work how you think it works. You more than likely want checkbox.checked as opposed to this.checked.

var checkbox = document.querySelector('input[type=checkbox]');
checkbox.addEventListener('change', function() {
  if (checkbox.checked) {
    document.body.classList.add('darkmode');
  } else {
    document.body.classList.remove('darkmode');
  }
});
.darkmode {
  background: black;
}
<input type="checkbox" />
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement