Rakesh Juyal Rakesh Juyal - 2 months ago 16
HTML Question

How to get the background color of an element using javascript?

How can i get the background color of any element, say Div, using javascript. I tried:-

<html>
<body>
<div id="myDivID" style="background-color: red">shit happens</div>
<input type="button" value="click me" onclick="getColor();">
</body>

<script type="text/javascript">
function getColor(){
myDivObj = document.getElementById("myDivID")
if ( myDivObj ){
alert ( 'myDivObj.bgColor: ' + myDivObj.bgColor ); // shows: undefined
alert ( 'myDivObj.backgroundcolor: ' + myDivObj.backgroundcolor ); // shows: undefined
//alert ( 'myDivObj.background-color: ' + myDivObj.background-color ); // this is not a valid property :)
alert ( 'style:bgColor: ' + getStyle ( myDivObj, 'bgColor' ) ); //shows: undefined
alert ( 'style:backgroundcolor: ' + getStyle ( myDivObj, 'backgroundcolor' ) ); // shows:undefined:
alert ( 'style:background-color: ' + getStyle ( myDivObj, 'background-color' ) ); // shows: undefined
}else{
alert ( 'damn' );
}
}
/* copied from `QuirksMode` - http://www.quirksmode.org/dom/getstyles.html - */
function getStyle(x,styleProp)
{
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
</script>
</html>

Answer

As with all css properties that contain hyphens, their corresponding names in JS is to remove the hyphen and make the following letter capital: backgroundColor

alert(myDiv.style.backgroundColor);