This question already has an answer here:
As I understand the getComputedStyles() method, it should return an object that allows one to access the actual CSS property values of an HTML element node.
I created this simple example with a paragraph containing a span:
let span = document.getElementsByTagName("span")[0];
let style = window.getComputedStyle(span);
span.innerText = "span background-color is " + style.getPropertyValue("background-color");
<p style="background-color: orange">
<span style="color: green">Empty</span>
</p>
The background color of the paragraph is orange
, so the span should also have that property value, or am I mistaken? Could it be that inherited values are ignored in getComputedStyles
? And if so, how can I get the actually visible background color for the span? Thank you.
It is giving you the correct result.
Note that the
a
inrgba
is0
. There is no opacity at all, the element is completely transparent.It isn't orange, you can just see through it to the orange element behind it.
if you use this
then you will get the font color
rgb(0, 128, 0)
as you use in span. your syntax giving you correct answer.EDIT: Updated my answer to use pure JS to find the background color you are looking for:
Another potential option would be updating your
style
of the span to inherit the background color of the parent, in which case your initial attempt would work:And here is the old version using Jquery:
This is done using recursion...may be this is what you want. It will keep checking its parent background-color until it finds one otherwise it will return transparent.
I have wrote this simple snippet to be sure that
getComputedStyle
returns only the applied style for the element, and not what is actually rendered.But, reading the defination of
getComputedStyle
from W3Schools, looks confusing, for me:Reading this, sounds like all "stylings" applied should be returned, and this is not what happens, just my opinion.