Reputation: 3579
Window.getComputedStyle()
returns a CSSStyleDeclaration
object with the resolved style properties of an element.
Is this object kept up-to-date as the page changes? For example, is this guaranteed to work?
var style = window.getComputedStyle(myDiv);
assert(myDiv.display == 'block');
myDiv.style.display = 'none';
assert(myDiv.style.display == 'none'); // Magically updated
I've noticed that the objects returned by calling getComputedStyle()
are not equal to each other. I assumed you couldn't cache the result of getComputedStyle()
since it's read-only. Will accessing properties always return the latest resolved value?
var style1 = window.getComputedStyle(myDiv);
myDiv.style.display = 'none';
var style2 = window.getComputedStyle(myDiv);
assert(style1 != style2); // Not the same object
for (var i = 0; i < style1.length; i++)
assert(style1[i] == style2[i]);
Upvotes: 3
Views: 1839
Reputation: 288680
According to the CSS Object Model, getComputedStyle
is defined as
partial interface Window { [NewObject] CSSStyleDeclaration getComputedStyle( Element elt, optional DOMString? pseudoElt ); };
Effectively, each time you call it, you get a different object. That's because of [NewObject]
:
If the
[NewObject]
extended attribute appears on a regular or static operation, then it indicates that when calling the operation, a reference to a newly created object MUST always be returned.
However, the returned declaration must be live:
Return a live CSS declaration block with the following properties:
- readonly flag: Set.
- declarations: All longhand properties that are supported CSS properties, in lexicographical order, with the value being the resolved value computed for obj using the style rules associated with doc.
- parent CSS rule: Null.
- owner node: obj.
The spec doesn't explicitly define what "live" means, but I guess it's reasonable enough.
Upvotes: 3
Reputation: 144739
Yes. getComputedStyle
returns a live
collection of CSS properties.
Each time the getComputedStyle
method is called a new object is returned and 2 objects are not considered equal in JavaScript, i.e.:
getComputedStyle(el) === getComputedStyle(el) // false
Just like {} === {} // false
. The properties of the collection is updated whenever the styles of the related element is changed. This means the computed property values of the 2 CSSStyleDeclaration
objects are equal but the 2 objects themselves are not equal.
cssStyleDeclaration1.color === cssStyleDeclaration2.color // true
The above code snippet returns true as it compares 2 strings (primitive values).
Upvotes: 4