Rakesh Juyal
Rakesh Juyal

Reputation: 36749

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">
    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>

Upvotes: 102

Views: 257008

Answers (8)

D&#39;Artagnan
D&#39;Artagnan

Reputation: 21

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/

Upvotes: 0

Husky931
Husky931

Reputation: 745

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/

Upvotes: 44

nemisj
nemisj

Reputation: 11980

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;

Upvotes: 12

Rehmat
Rehmat

Reputation: 2299

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");

Upvotes: 9

phnghue
phnghue

Reputation: 1686

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

Upvotes: 126

user228807
user228807

Reputation: 289

With jQuery:

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

With prototype:

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

With pure JS:

document.getElementById("myDivID").style.backgroundColor

Upvotes: 28

Aziz
Aziz

Reputation: 20705

Using JQuery:

var color = $('#myDivID').css("background-color");

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129792

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);

Upvotes: 56

Related Questions