+ 2

Why am I getting this error?

The code in question https://code.sololearn.com/WoF6VRI7VNPP/?ref=app The commented version on the JS tab DON'T work, but in my opinion it should, why should I declare the variable where I include the element I'm querying inside the function? That was never I thing in my previous codes, why is it now?

12th Mar 2022, 7:21 PM
Juvenal Martins dos Santos Netto
Juvenal Martins dos Santos Netto - avatar
6 Respostas
+ 6
Could it be that var bulb = document.querySelector("#bulb") is executing before the DOM is done loading?
12th Mar 2022, 10:05 PM
Paul K Sadler
Paul K Sadler - avatar
+ 3
SoloProg solution didn't work for me, but Paul K Sadler was right, using: document.onload = () => {const bulb = document.querySelector("#bulb")}; anywhere in the code (above or below the function, arrow or not arrow) makes it work, thanks guys!
12th Mar 2022, 10:39 PM
Juvenal Martins dos Santos Netto
Juvenal Martins dos Santos Netto - avatar
+ 3
Awesome!
12th Mar 2022, 10:44 PM
Paul K Sadler
Paul K Sadler - avatar
+ 3
You used radio button. Better to use checkbox. or ordinary button. this way it will be similar to real world. You can switch on or switch off
13th Mar 2022, 3:23 AM
Shadoff
Shadoff - avatar
+ 3
Paul K Sadler Nice pick up buddy
13th Mar 2022, 9:05 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
// try it var bulb = document.querySelector("#bulb"); lightOn = () => { bulb.style.backgroundColor = "yellow"; }
12th Mar 2022, 9:42 PM
SoloProg
SoloProg - avatar