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