Retrieving background-color Property of CSS Elements

by kalai 2008-04-30 20:19:34

This describes a method for retrieving the background-color values of a html element

In Mozilla browsers (like Firefox), the color can be retrieved using
getComputedStyle(element, psedoStyleString).

For example, to get the background-color for this <div>,

A <div> with yellow background rgb(255,255,0) or #ffff00.

you'd use:
var element=document.getElementById("testDiv");
var style=window.getComputedStyle(element,"");
var bgColor=style.getPropertyValue("background-color");

Now, combining the two methods:

function getBgColor(element)
{
if (element.currentStyle)
return element.currentStyle.backgroundColor;
if (window.getComputedStyle)
{
var elementStyle=window.getComputedStyle(element,"");
if (elementStyle)
return elementStyle.getPropertyValue("background-color");
}
// Return 0 if both methods failed.
return 0;
}

Tagged in:

1932
like
0
dislike
0
mail
flag

You must LOGIN to add comments