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 beinput
- You should be looking for
type=checkbox
instead ofname=checkbox
this.checkbox
probably doesn’t work how you think it works. You more than likely wantcheckbox.checked
as opposed tothis.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" />