77

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>
double-beep
  • 4,567
  • 13
  • 30
  • 40
Rakesh Juyal
  • 34,491
  • 66
  • 168
  • 213
  • 11
    Note that the (currently) accepted answer will only work under a very restricted set of circumstances. – NickFitz Dec 11 '09 at 11:09

7 Answers7

106

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
SierraOscar
  • 17,307
  • 5
  • 38
  • 67
phnghue
  • 1,342
  • 2
  • 9
  • 9
  • 2
    `null` can be not written – Eric Mar 23 '18 at 11:36
  • 2
    The second parameter is an optional property used to specify the pseudo element, so it can be safely omitted. See the documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle – natsuozawa Apr 06 '19 at 09:37
  • 1
    Please be aware that this is a very expensive operation. Use with caution! – connexo Mar 26 '22 at 16:15
51

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);
David Hedlund
  • 125,403
  • 30
  • 199
  • 217
  • David will you please let me know why `getStyle` is used in `http://www.quirksmode.org/dom/getstyles.html`, when it was so easy to get the style property. – Rakesh Juyal Dec 11 '09 at 10:37
  • 1
    well the page you link to has some descriptions in itself as to what it's good for. for mozilla, for instance, it uses `getComputedStyle`, which is not so much what's specified in the stylesheet, but rather, what happens to be displayed, both as a result of HTML markup *and* CSS styling. For something as simple as this scenario, though, I don't see any really good reason to use that function. – David Hedlund Dec 11 '09 at 10:44
  • 52
    The `style` property only contains styles assigned in a `style` attribute or set by scripting. Styles set in a `style` element or an external stylesheet won't be found there, at which point you need different techniques for different browsers (standard techniques for everything but IE, as usual) which ppk's `quirksmode` script will take care of. – NickFitz Dec 11 '09 at 11:08
27

Simple solution

myDivObj = document.getElementById("myDivID")
let myDivObjBgColor = window.getComputedStyle(myDivObj).backgroundColor;

Now the background color is stored in the new variable.

https://jsfiddle.net/7q1dpeo9/1/

terary
  • 780
  • 11
  • 28
Husky931
  • 516
  • 5
  • 10
  • 4
    As opposed to the accepted answer, this gives the color even if it is assigned through a class. – JoSSte Apr 03 '20 at 14:57
23

With jQuery:

jQuery('#myDivID').css("background-color");

With prototype:

$('myDivID').getStyle('backgroundColor'); 

With pure JS:

document.getElementById("myDivID").style.backgroundColor
Tony Stark
  • 7,934
  • 8
  • 43
  • 63
user228807
  • 239
  • 1
  • 2
12

It depends which style from the div you need. Is this a background style which was defined in CSS or background style which was added through javascript(inline) to the current node?

In case of CSS style, you should use computed style. Like you do in getStyle().

With inline style you should use node.style reference: x.style.backgroundColor;

Also notice, that you pick the style by using camelCase/non hyphen reference, so not background-color, but backgroundColor;

nemisj
  • 10,564
  • 2
  • 24
  • 23
10

This worked for me:

var backgroundColor = window.getComputedStyle ? window.getComputedStyle(myDiv, null).getPropertyValue("background-color") : myDiv.style.backgroundColor;

And, even better:

var getStyle = function(element, property) {
    return window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(property) : element.style[property.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); })];
};
var backgroundColor = getStyle(myDiv, "background-color");
Rehmat
  • 1,807
  • 2
  • 20
  • 25
3

Using JQuery:

var color = $('#myDivID').css("background-color");
Aziz
  • 19,084
  • 5
  • 61
  • 68
  • the div before the id selector is a little redundant – AutomatedTester Dec 11 '09 at 10:21
  • 23
    downloading and executing a 20kb library for retrieving the background color of a DIV is a little redundant ;) – David Hedlund Dec 11 '09 at 10:26
  • @David: sorry david, though i wanted to give you +20 reps but SO is not allowing me to do so :). +1 for you. Agree altogether. – Rakesh Juyal Dec 11 '09 at 10:33
  • 2
    well, if the only javascript used in the whole page is to get the background color, then it is redundant, but usually a page has much more things done in javascript, which makes using JQuery a little reasonable. – Aziz Dec 11 '09 at 19:18
  • 2
    Those who want to avoid jQuery will find [this blog](http://acuriousanimal.com/blog/2012/07/09/look-mom-no-jquery-getting-all-css-properties-of-a-dom-element-in-pure-javascript/) useful. In short: you have to go into browser-specific details/features. – robert4 Nov 14 '13 at 12:30