getComputedStyle returns a CSSStyleDeclaration but all properties are empty on access
Asked Answered
S

1

16

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

Shayneshays answered 12/2, 2016 at 10:51 Comment(2)
Can you replicate the issue in a JSFiddle or CodePen?Talent
Thank you @Talent . I sat down today with JSFiddle for the first time, and I found the solution as a result.Shayneshays
S
13

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.

Shayneshays answered 16/2, 2016 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.