eawedat
eawedat

Reputation: 417

what's wrong with this javascript code getElementById?

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

Answers (5)

mbunch
mbunch

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

Quentin
Quentin

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

acolchado
acolchado

Reputation: 541

2 things that need to change in your code.

  1. 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.

  2. 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

Wilhelm Kleu
Wilhelm Kleu

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

Userbn
Userbn

Reputation: 342

You should write backgroundColor

Upvotes: 2

Related Questions