What's Wrong With This Javascript Code GetElementById?
Solution 1:
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).
Solution 2:
You should write backgroundColor
Solution 3:
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.
Solution 4:
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>
Solution 5:
Update:
<div id="example">This is an example.</div>
<script>document.getElementById('example').style.setProperty('background-color','#fco','important');</script>
,'important' is not required
Post a Comment for "What's Wrong With This Javascript Code GetElementById?"