Forum Moderators: open

Message Too Old, No Replies

Get the background color of a DIV doesn't work

         

maa123

4:16 pm on Jan 31, 2008 (gmt 0)

10+ Year Member



Hi,

I don't understand where's the problem. The following code displays background color of DIV2 but not the one of DIV1. Please try it.

<style>
#div1{ background-color:#333333}
</style>
<div id="div1" >asdf</div>
<div id="div2" style="background-color:#666666">asdf</div>

<script>
window.onload= function(){

var color1 = document.getElementById("div1").style.backgroundColor;
var color2 = document.getElementById("div2").style.backgroundColor;
alert(color1)
alert(color2)
}
</script>

Trace

4:21 pm on Jan 31, 2008 (gmt 0)

10+ Year Member



I think what you need to do is this;

var color1 = document.getElementById("div1").currentStyle['backgroundColor'];

but that's only for Internet Explorer. For all other browsers, use this;

var color1 = document.getElementById("div1").getPropertyValue('background-color');

Fotiman

4:38 pm on Jan 31, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The reason it doesn't work is because this:

document.getElementById("div1").style.backgroundColor;

is accessing the value assigned to the 'style' attribute. It does not references all styles for that object.

maa123

4:44 pm on Jan 31, 2008 (gmt 0)

10+ Year Member



Thanks Trace, it works perfect in IE! And thanks Fotiman for the precision.

For Firefox I found this :

var color1 = window.getComputedStyle(document.getElementById("div1"),null).backgroundColor;

Thanks again!