Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialB D
2,703 PointsCan't use js to make div background black?
I can't seem to make js change the background color of a div.
Here's what's in my html file:
<script src="script.js"></script>
<div class="myDiv">
<p>F javascript.</p>
</div>
And here's what's in my script.js file:
document.getElementById('myDiv').style.background = "black";
Not sure what I'm doing wrong? Thx in advance.
B D
2,703 PointsThanks for the input. It turns out that both your code and my code for that line in particular work just fine. I had the div in my html labeled as a class, and I had the js script loading before the div instead of after (so the js script would know what 'myDiv' was). Thanks again for your help.
2 Answers
B D
2,703 PointsI had the div in my html labeled as a class, and I had the js script loading before the div instead of after (so the js script would know what 'myDiv' was).
Adiv Abramson
6,919 PointsWhere would we want to use code like this, given that CSS can do the same thing? Perhaps in response to a particular event or condition that can't be detected by CSS code? Thanks
Michael Escoto
30,028 PointsMichael Escoto
30,028 PointsYou need to use document.getElementById('myDiv').style.backgroundColor = "black";