Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get actual CSS property value of an HTML element node? [duplicate]

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.

like image 443
Krisztián Balla Avatar asked Jan 09 '18 11:01

Krisztián Balla


People also ask

How do you retrieve a CSS property value of an element?

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.

How do you get all of the CSS properties of an element in JavaScript?

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.

What does the window getComputedStyle () method return?

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.

How do you clone a node in HTML?

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


1 Answers

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.

like image 197
Quentin Avatar answered Oct 13 '22 03:10

Quentin