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">shit happens</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.log('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>
HTML color codes are hexadecimal triplets representing the colors red, green, and blue (#RRGGBB). For example, in the color red, the color code is #FF0000, which is '255' red, '0' green, and '0' blue. There are 16,777,216 possible HTML color codes, and all are visible on a 24-bit display.
Get at number:
window.getComputedStyle( *Element* , null).getPropertyValue( *CSS* );
Example:
window.getComputedStyle( document.body ,null).getPropertyValue('background-color'); window.getComputedStyle( document.body ,null).getPropertyValue('width'); ~ document.body.clientWidth
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);
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