Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the background color of an HTML element?

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>
like image 821
Rakesh Juyal Avatar asked Dec 11 '09 10:12

Rakesh Juyal


People also ask

How do I find the HTML color code?

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.


2 Answers

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 
like image 123
phnghue Avatar answered Oct 08 '22 14:10

phnghue


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); 
like image 27
David Hedlund Avatar answered Oct 08 '22 14:10

David Hedlund