How can I get the background color of any element, like a <div>
, using JavaScript? I have tried:
<html>
<body>
<div id="myDivID" style="background-color: red">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
<input type="button" value="click me" onclick="getColor();">
</body>
<script type="text/javascript">
function getColor() {
myDivObj = document.getElementById("myDivID")
if (myDivObj) {
console.log('myDivObj.bgColor: ' + myDivObj.bgColor); // shows: undefined
console.log('myDivObj.backgroundcolor: ' + myDivObj.backgroundcolor); // shows: undefined
//alert ( 'myDivObj.background-color: ' + myDivObj.background-color ); // this is not a valid property :)
console.log('style:bgColor: ' + getStyle(myDivObj, 'bgColor')); //shows: undefined
console.log('style:backgroundcolor: ' + getStyle(myDivObj, 'backgroundcolor')); // shows:undefined:
console.log('style:background-color: ' + getStyle(myDivObj, 'background-color')); // shows: undefined
} else {
console.error('Error: When function "getColor();" was called, no element existed with an ID of "myDivId".');
}
}
/* 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>