I have the following code below that I'm trying to set a background color. However, the background color returns as an empty string. I'm not sure why...Does it have something to do with javascript types?
function function1(){
var color = document.getElementById('rg_vw.national_avg').style.backgroundColor;
//this below appears as an empty alert at runtime. it's an empty string.
alert(color)
}
Just as a sanity check, if I use the 'value' property, it prints out the correct value for that particular field...so I'm just a bit frustrated as to why the backgroundColor is an empty string.
//this works just fine
var value = document.getElementById('rg_vw.national_avg').value
alert(value)
Unless you have directly defined the backgroundColor on the element itself, you have to use getComputedStyle()
or currentStyle
to get the value of a style property.
A method that is compatible with multiple browsers would look like this:
function getStyle(el,styleProp)
{
if (el.currentStyle)
return el.currentStyle[styleProp];
return document.defaultView.getComputedStyle(el,null)[styleProp];
}
You can see a working example on jsFiddle.
More information:
getComputedStyle()
.currentStyle
(IE).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With