How to get the background color of an HTML element?
Asked Answered
J

8

99

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>
Jegar answered 11/12, 2009 at 10:16 Comment(1)
Note that the (currently) accepted answer will only work under a very restricted set of circumstances.Priscian
I
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);
Indicative answered 11/12, 2009 at 10:18 Comment(3)
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.Jegar
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.Indicative
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.Priscian
M
126

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
Metamerism answered 23/9, 2014 at 9:44 Comment(3)
The second parameter is an optional property used to specify the pseudo element, so it can be safely omitted. See the documentation here: developer.mozilla.org/en-US/docs/Web/API/Window/…Eviscerate
Please be aware that this is a very expensive operation. Use with caution!Crispation
This won't work with pseudo-class, such as ":hover".Thissa
I
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);
Indicative answered 11/12, 2009 at 10:18 Comment(3)
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.Jegar
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.Indicative
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.Priscian
K
40

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/

Kimberly answered 11/12, 2019 at 3:7 Comment(1)
As opposed to the accepted answer, this gives the color even if it is assigned through a class.Mares
S
27

With jQuery:

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

With prototype:

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

With pure JS:

document.getElementById("myDivID").style.backgroundColor
Scoles answered 11/12, 2009 at 11:18 Comment(0)
G
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;

Gabbey answered 11/12, 2009 at 10:24 Comment(0)
S
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");
Selfimportant answered 2/7, 2018 at 13:49 Comment(0)
B
2

Using JQuery:

var color = $('#myDivID').css("background-color");
Bandwidth answered 11/12, 2009 at 10:19 Comment(4)
the div before the id selector is a little redundantSamalla
downloading and executing a 20kb library for retrieving the background color of a DIV is a little redundant ;)Indicative
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.Bandwidth
Those who want to avoid jQuery will find this blog useful. In short: you have to go into browser-specific details/features.Hephzipah
M
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/

Mesomorph answered 11/5, 2023 at 17:17 Comment(1)
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?Ab

© 2022 - 2024 — McMap. All rights reserved.