Why is my button not changing the bgcolor of my div? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is my button not changing the bgcolor of my div?

I have a div with id "facebook" and a button with id "btn". I was expecting the background-color of my Facebook div to change to the color I set when the btn is clicked using JavaScript but obviously nothing happens. What is the problem? https://code.sololearn.com/Wf95x98xmqja/?ref=app

4th Oct 2021, 12:42 PM
DN Josh
DN Josh - avatar
2 Answers
+ 2
Hey buddy, that happens because your button doesn't exist yet when your JS code executes (html has not being loaded yet) To fix that you could use window.onload, just like that: https://code.sololearn.com/W5d9by3w9TqM/?ref=app (that function makes your code execute only when html has been fully loaded)
4th Oct 2021, 12:49 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
You'll find the answer in this post https://www.sololearn.com/post/90825/?ref=app
4th Oct 2021, 12:48 PM
Ipang