Forum Moderators: open

Message Too Old, No Replies

Getting backgroundColor with JavaScript

(element using css class)

         

vol7ron

6:43 pm on Sep 29, 2009 (gmt 0)

10+ Year Member



I don't want to spend too long searching for this, so hope someone knows.

I'm trying to get the background color off an element. The element's background color is defined in the class. The following is a simplified example, that returns an empty string:

[pre]
<td class="someClass" style="border:1px solid black;">

// obj is correctly referencing the td
alert(obj.style.backgroundColor); // returns empty string
alert(obj.style.border); // returns the correct border

// class set up something like the following
.someClass{
background: #ccc;
}
[/pre]

Because it's returning an empty string (w/o error), it recognizes obj exists and backgroundColor is being called correctly - the nodeName is also returning correctly and className is also returning 'someClass', so the obj is right. In firebug, element.style has no background associated with it; however, .someClass does

Thanks,
vol7ron

vol7ron

6:58 pm on Sep 29, 2009 (gmt 0)

10+ Year Member



Nevermind, I came up with a workaround:
[pre]
var color = (document.defaultView)
? document.defaultView.getComputedStyle(obj,null).getPropertyValue('background-color')
: obj.currentStyle['backgroundColor'];
alert(color);
[/pre]

Hope this helps someone else down the road. currentStyle/backgroundColor is IE, defaultView/background-color is everyone else.

vol7ron