This was a surprise. The following code does not seem to give me the actual colors on the screen:
h1 = document.querySelector("h1");
window.getComputedStyle(h1).color
Gives rgb(0, 0, 0)
which I think is correct. However
window.getComputedStyle(h1).backgroundColor
gives rgba(0, 0, 0, 0)
. The actual background color I see on the screen is white.
The element I call h1 is visible on the screen. I was expecting to get the actual background color. The value I get above (in rgba) is not wrong, but not very useful either. It just tells me the background is fully transparent - and that is not a color.
How do I get the actual background color in RGB?
If you set your background-color: rgba(255, 255, 255,
0
) in your css;getComputedStyle()
will returntransparent
(in some browsers) instead of your rgba value.Easy fix for this is setting alpha to something higher than 0 for example rgba(255, 255, 255,
0.01
); This will return rgba(255, 255, 255,0.01
)getComputedStyle(h1)
provides the css value of element after applied in active stylesheet.Which means you can get those css value only which applied to particular element in any way.
Eg:- if you applied background for
h1 :RGB{255, 255, 255},
then you will get the background color white in rgb format otherwise not. It does not provide value for html's default style.To get the value by
getComputedStyle()
, First you should apply this to element.For more info getComputedStyle()