95

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>
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Rakesh Juyal
  • 35,919
  • 68
  • 173
  • 214
  • 11
    Note that the (currently) accepted answer will only work under a very restricted set of circumstances. – NickFitz Dec 11 '09 at 11:09

8 Answers8

122

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,507
  • 6
  • 40
  • 68
phnghue
  • 1,578
  • 2
  • 10
  • 9
  • 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
54

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
  • 128,221
  • 31
  • 203
  • 222
  • 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
  • 56
    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
37

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
  • 940
  • 13
  • 30
Husky931
  • 636
  • 6
  • 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
26

With jQuery:

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

With prototype:

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

With pure JS:

document.getElementById("myDivID").style.backgroundColor
Tony Stark
  • 8,064
  • 8
  • 44
  • 63
user228807
  • 269
  • 2
  • 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
  • 11,562
  • 2
  • 25
  • 23
9

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
  • 2,121
  • 2
  • 24
  • 28
2

Using JQuery:

var color = $('#myDivID').css("background-color");
Aziz
  • 20,065
  • 8
  • 63
  • 69
  • the div before the id selector is a little redundant – AutomatedTester Dec 11 '09 at 10:21
  • 24
    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
  • 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
0

You can draw a canvas element over you control, even without display it, to get the color at a specific position in you controls, if it has many colors.

<head>
    <style>
    </style>
</head>
<body><div style="border:gray solid 2px;height:575px;width:700px;position:absolute;top:75px;right:15px;background:black;color:white;font-Family:Century SchoolBook;font-Size:18px;padding-Top:20px;" id="container101"><div id="header" style="text-Align:center">ColorPicker</div> 
    <div id="div101" style="position:absolute;top:60px;left:100px;width:500px;height:500px;"></div> 
    <canvas height="500" width="500" style="position:absolute;top:60px;left:100px;display:none;" id="canva"></canvas>

</div>

<script>
    function create(r1,g1,b1,r2,g2,b2){dv101 = 
    document.querySelector("#div101");dv101.style.background = "linear-gradient(90deg, rgb("+r1+", "+g1+", "+b1+"), rgb("+r2+", "+g2+", "+b2+"))";
    var can = document.querySelector("#canva");
    var context = can.getContext("2d");
    context.rect(0, 0, 500, 500);
    var grd = context.createLinearGradient(0,0,can.width,0);
    grd.addColorStop(0, "rgb("+r1+", "+g1+", "+b1+")");
    grd.addColorStop(1, "rgb("+r2+", "+g2+", "+b2+")");
    context.fillStyle = grd;
    context.fillRect(0,0,500,500);

    dv101.onmousemove = (event) => {
        var posx = event.clientX-dv101.offsetLeft- 
        document.querySelector("#container101").offsetLeft;
        var posy = event.clientY-dv101.offsetTop- 
        document.querySelector("#container101").offsetTop;
        console.log(posx,posy);
        var data = context.getImageData(posx,posy,1,1);
        couleur = "rgb("+data.data[0]+","+data.data[1]+","+data.data[2]+")";
        document.body.style.background=couleur;
    } return couleur;
};create(255, 0, 0, 0, 0, 255);
var arr = new Array();
function inp(x,y){
    var input1 = document.createElement('input');
    var cont = document.querySelector("#container101");
    cont.appendChild(input1);
    arr.push(input1);
    input1.type = "text";
    input1.style = "outline:none;position:absolute;top:"+y+"px;left:"+x+"px;height:30px;width:60px;background:white;color:black;";
    input1.value = 0;
    input1.onkeydown = (event) => {

        switch(event.keyCode){

        case 38:
            input1.value++;
            create(arr[0].value, arr[1].value, arr[2].value, arr[3].value, arr[4].value,arr[5].value);
            break;

        case 40:
            input1.value--;
            create(arr[0].value, arr[1].value, arr[2].value, arr[3].value, arr[4].value,arr[5].value);
            break;
        };
    }
};inp(5,60);inp(5,110);inp(5,160);inp(610,60);inp(610,110);inp(610,160);
</script>
</body>
</html>

This is a working fiddle. https://jsfiddle.net/cdgpts9n/

B25Dec
  • 2,301
  • 5
  • 31
  • 54
D'Artagnan
  • 11
  • 3
  • Please provide formatted code. Also, the question is about getting the background color of an HTML element, but I think your answer is about selecting a color from a canvas with the mouse - that's something else entirely, isn't it? – Moritz Ringler May 13 '23 at 11:19