GetComputedStyle returns CSSStyleDeclaration, but all properties are empty upon access

I have a simple div that uses the css class, which in turn has the color and background-color properties.

 var div = document.createElement("div"); div.classList.add("my-css-class"); container.appendChild(div); //This prints out a CSSStyleDeclaration object. This is a large object to which I see `color` and `backgroundColor` console.log(getComputedStyle(div)); //this gives me an empty string console.log(getComputedStyle(div).color); //this gives me an empty string console.log(getComputedStyle(div).getPropertyValue("color")); 

Why can't I access CSSStyleDeclaration properties? I know this is from my first magazine. I see color: "rgb(82, 194, 145)"

+5
source share
1 answer

Ultimately, the problem with getComputedStyle is that it seems that this element should be part of the DOMTree for any style to be available.

Please note that in my case, I added the div to the parent container, however, the parent container was not yet added to the DOMTree when the instance was created.

My failure to use JSON.stringify() to print the object meant that the values โ€‹โ€‹appeared later but were empty during access.

Basically, I temporarily changed my container.appendChild to document.body.appendChild in order to calculate the style I need, and then delete it and destroy it, leaving me only the colors I need.

+5
source

Source: https://habr.com/ru/post/1242855/


All Articles