How to Get the Background Color of an HTML Element

How to get the background color of an HTML element?

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

How can I set an element's background-color in an HTML file?

You are using two style attributes on a single div element, which is invalid:

<div style="height:100px;" style="background-color:red;">text</div>

Instead, use (if using different CSS styles, separate them by ; like below)

<div style="height:100px;background:red;">text</div>

You can use inline CSS in the HTML, or by using the bgColor attribute.

You can use the bgColor attribute, like bgColor="#6B6B6B", in the body element to change the background-color of <body>.

The HTML bgcolor attribute is used to set the background color of an HTML element. Bgcolor is one of those attributes that has become deprecated with the implementation of Cascading Style Sheets.

It Supports tags like

<body>,<marquee>, <table>, <tbody>,<td>,<tfoot>,<th>,<thead>,<tr>

DEMO USING bgColor:

<body bgColor="#6B6B6B">
<div style="height:100px;background:red;">text</div>
</body>

How to get the background color of an element (set to RGBA) in Javascript?

I will consider this answer where I am detailing how the color is calculated between two layers to write the following script.

/* Utility function that you can easily find in the net */
function extractRgb (css) {
return css.match(/[0-9.]+/gi)
}
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
/**/

var c = window.getComputedStyle(document.getElementById('box')).backgroundColor;
c = extractRgb(c);

for(var i=0;i<3;i++)
c[i] = parseInt(c[i]*c[3] + 255*(1 - c[3])); /* Check the linked answer for details */

console.log(rgbToHex(c[0],c[1],c[2]) )
#box {
width: 100px;
height: 100px;
margin: 10px;
background-color: rgba(0, 0, 0, 0.3);
}
<div id="box"></div>

Getting a Html element background Color With JS

element.style only returns the inline style attributes (see here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style#Notes)

You might be better off using window.getComputedStyle(). That however returns an RGB color which you might want to convert to hex if you desire.

function setCor(x) {
cor = window.getComputedStyle(x, null)['background-color'];
}

JavaScript checking the background color of a div

The result of querySelectorAll is not a complete array. It is more like an "array like" object. But it does not support every (or forEach, or map ...).

But you can make it a real array with Array.from.

But in your code you only do Array.from(box);. But this code does nothing because box will not be modified. You have to write box = Array.from(box); or use it directly:

Array.from(box).every(function(div) {
return div.style.backgroundColor == 'blue' || div.style.backgroundColor == 'red';
});

How to get `background-color` property value in Javascript?

The reason you're not seeing anything from .style is that that only gives you the styles set on the element, not ones it receives from stylesheets.

For modern browsers, you can use window.getComputedStyle to get the computed style object for the element. For IE8 (and earlier, but...), you can use .currentStyle to get much the same thing. So:

var element = document.getElementById('test');
var style;
if (window.getComputedStyle) {
style = window.getComputedStyle(element);
} else {
style = element.currentStyle;
}
if (!style) {
// ...seriously old browser...
} else {
alert(style.backgroundColor);
}

I just want to get stylesheet value.

getComputedStyle/currentStyle will give you that, but will also give you the browser's default style.

There's no simple interface to get only the value from your own stylesheets and not from the user agent's default stylesheet. You might want to look at the document.styleSheets property, which gives you access to the individual parsed stylesheets and their rules. But you'd have to handle the logic of applying those rules to the element in question, which is (of course) non-trivial.

How to get the global css background-color at a specific position using javascript

Example using html2canvas and canvas.getImageData

I created an example using html2canvas library. This library will generate an image of the website and store it in a canvas (this canvas we get in a variable and is not visible on the site). With canvas.getImageData you can get the color on the image of a certain pixel at a certain offset.

Update nov 14; performance improvement

I have updated the script so there is only one print screen loaded on page load. Also when a rbg color is obtained, it is stored in a global array to improve performance, the next time it is loaded from the array.

Example

See a working example at https://833964.playcode.io/

Explanation

The function below renders an image using html2canvas, a printscreen of the website. After the image is loaded by html2canvas we can obtain the color of a certain pixel at a certain offset.

Code

<html>
<head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.3.2/html2canvas.min.js"></script>
</head>

<body style="margin: 0px; padding: 0px;">

<div style="width: 100%; position: fixed; background-color: #000;height: 69px;">
<h1 style="color: #fff; width: 500px; float:left;">Color box (on the right)</h1>
<span style="width: 30px; height: 30px; float:right" id="colorDisplay"></span>
</div>

<div style="height:550px; background-color:#00ff00;width:100%"></div>
<div style="height:550px; background: linear-gradient(0deg, rgba(34,193,195,1) 0%, rgba(253,187,45,1) 100%);width:100%"></div>
<div style="height:550px; background-color:#0f0f0f;width:100%"></div>
<div style="height:1050px; background-color:#ff0000;width:100%"></div>

<script>
window.canvas = null;
window.canvasContext = null;
window.rgb = [];

function debounce(func, timeout)
{
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}

function setColor(offsetY)
{
var p = null;
if(window.canvas == null) {
//... nothing
} else {
if(window.canvasContext == null){
window.canvasContext = window.canvas.getContext('2d');
}
if(window.rgb[offsetY] !== undefined) {
p = window.rgb[offsetY];
} else {
p = window.canvasContext.getImageData(1, 70 + offsetY, 1, 1).data;
window.rgb[offsetY] = p;
}
document.getElementById("colorDisplay").style.backgroundColor = "rgb(" + p[0]+", "+p[1]+", "+p[2] + ")";
}
}

function loadCanvas()
{
html2canvas(document.body, {scale: '1', scrollY: 0}).then((canvas) => {
window.canvas = canvas;
setColor(window.pageYOffset);
});
}

(function(){
loadCanvas();
window.onscroll = debounce(() => setColor(window.pageYOffset), 10);
})();

</script>
</body>
</html>

Note

If a window resize changes the layout of your website, so that colors don't match anymore, you can consider reloading the canvas. You can do this with this script:

window.addEventListener('resize', function(event) {
window.canvas = null;
window.canvasContext = null;
window.rgb = [];
loadCanvas();
}, true);

Getting the real background-color of an element?

Try window.getComputedStyle:

window.getComputedStyle(element, null).getPropertyValue("background-color")

This approach is simple and native, but doesn't support IE8

How to get backgroundColor of element when it is set by the CSS property background?

When you access the style (ElementCSSInlineStyle.style) property of an element, you are accessing its inline style. This means that if you give an element a style via a class, you still cannot access it through style. As a result, it will return you an empty string ('').

Window.getComputedStyle, on the other hand, returns:

... the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain

This means that you can access the style that is given via a class, simply because it gives you all CSS properties after applying all active stylesheets (including those applied via a class).

In your particular case, you're trying to access background. background CSS property is actually a shorthand that also sets a lot of other background-related CSS properties. When you specify only the color using background, the other properties will automatically be inserted with their default values. You can access this background property through ElementCSSInlineStyle.style. However, when accessing background in the object Window.getComputedStyle returns, you will always get an empty string. This is because the object returned does not have the key background; it only has the keys for each background-related CSS properties (e.g. background-color, background-clip, etc.).

Here's a simple example demonstrating how you cannot access a non-inline style through style property of an element, and also how you cannot access the value of a property that is shorthand through the object Window.getComputedStyle

const boxOne = document.querySelector('#boxOne')const boxTwo = document.querySelector('#boxTwo')
console.log(`Box One: background ${boxOne.style['background']}, background-color ${boxOne.style['background-color']}`)
console.log(`Box Two: background ${boxTwo.style['background']}, background-color ${boxTwo.style['background-color']}`)
const boxOneComputedStyles = getComputedStyle(boxOne)const boxTwoComputedStyles = getComputedStyle(boxTwo)
// There's no 'background' key in getComputedStyle
console.log(`Box One (Computed Styles): background ${boxOneComputedStyles['background']}, background-color ${boxOneComputedStyles['background-color']}`)
console.log(`Box Two (Computed Styles): background ${boxTwoComputedStyles['background']}, background-color ${boxTwoComputedStyles['background-color']}`)
#boxOne,#boxTwo {  background: #121212DD;  border-radius: 5px;  width: 50px;  height: 50px;  margin: 1em;}
<div id="boxOne" style="background-color: #121212DD;"></div><div id="boxTwo" style="background: #121212DD;"></div>


Related Topics



Leave a reply



Submit