Reputation: 417
I have this code below..
<script> document.getElementById('example').style.background-color =
'#FFCC00';
</script>
<div id="example">This is an example.</div>
why does not it work?
Upvotes: 0
Views: 1136
Reputation: 569
Update:
<div id="example">This is an example.</div>
<script>document.getElementById('example').style.setProperty('background-color','#fco','important');</script>
,'important' is not required
Upvotes: 0
Reputation: 943480
The script runs before the element with the given id exists, and you have a DOM property name with a hyphen in it (which gets treated as the minus operator).
<!-- Put the element first -->
<div id="example">This is an example.</div>
<script>
// camelCase CSS property names when converting to DOM property names
document.getElementById('example').style.backgroundColor = '#FFCC00';
</script>
See a live example of the above snippit.
Instead of putting the element first, you can wrap your JS statement in a function and then call it after the element exists. You can have this happen automatically by binding it as an event handler to something suitable (such as the document load event).
Upvotes: 7
Reputation: 541
2 things that need to change in your code.
As is, your code is in the wrong order. You need to have the HTML first and then the JS. The element doesn't yet exist in this order, the JS is being executed first and the DOM object is not yet there.
There is no "background-color" property. Instead use ".backgroundColor". The dashes are usually replaced with camel casing.
Here is a working example:
<div id="example">This is an example.</div>
<script>
document.getElementById('example').style.backgroundColor = '#FFCC00';
</script>
Another tip:
If you want to remove the order as a dependency, you can wrap the JavaScript in a "onload" event handler.
Upvotes: 1
Reputation: 11047
Change the <script>
to be below your element and use backgroundColor
<div id="example">This is an example.</div>
<script>
document.getElementById('example').style.backgroundColor ='#FFCC00';
</script>
Upvotes: 0