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.
First, you need to select the element with querySelector . Then, you use getComputedStyle to get the element's styles. If you log style , you should see an object that contains every CSS property and their respective values. You can also see this object in Chrome's and Firefox's dev tools.
The CSS of an element can be obtained using the getComputedStyle element function in JavaScript. It returns a JavaScript object containing CSS properties and their values. This object is indexed and iterable over the property names. The getPropertyValue(property) is used to get the value of a property.
The Window. getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.
The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).
It is giving you the correct result.
span background-color is rgba(0, 0, 0, 0)
Note that the a
in rgba
is 0
. 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With