Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getComputedStyle returns a CSSStyleDeclaration but all properties are empty on access

I have a simple div that uses a css class which in turn has a color and background-color property set.

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 am I unable to access the properties of the CSSStyleDeclaration? I know it is there from my first log. I can see color: "rgb(82, 194, 145)"

like image 484
Clark Avatar asked Feb 12 '16 10:02

Clark


1 Answers

Ultimately the problem with getComputedStyle is that it appears that the element in question must be a part of the DOMTree in order for any style to be available.

Notice in my case, I was adding the div to the parent container, however, the parent container at the point of instantiation is not yet added to the DOMTree.

My failure to use JSON.stringify() to print the object meant that values were appearing later but at the time of access, were blank.

So basically, I changed my container.appendChild to document.body.appendChild temporarily to compute the style I need straight away, and then remove it and destroy it leaving me just the colors I needed.

like image 143
Clark Avatar answered Oct 31 '22 06:10

Clark