1

A CSS class applies properties to a div object. As expected, when that object has been given that class, it now has the properties supplied by the class (width, height, and some margins).

Now, I can check the style properties of an object with the following code:

var object = document.getElementById('myObject').style;

When the style property of the object is looked at with javascript, the style property does not show the styles that were added by the class. For each of the width, height, and respective margin properties, the style property of the object has not been updated.

I can clearly see that the object has the properties supplied by it's class: I can see this both on the webpage and also in the developer tools. But the style property of the object does not match up with what I'm seeing on the page.

The observation: when a CSS class is applied to an object, the class applies it's styling to update how the object is displayed, but it does not change the properties of the object.

..

This is ok, I suppose, but what do I do if I want to check, with javascript, the exact width of the object as it appears when styled with a class? Is this possible, and if so what does the code look like?

Max
  • 808
  • 11
  • 25

1 Answers1

2

It sounds like you're after getComputedStyle().

The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.

Marty
  • 39,033
  • 19
  • 93
  • 162
  • That was exactly what I needed! Although I am just working on a small personal project, I have testing code for my company that could use this, as I had previously run into this problem while writing test cases. Thanks for the help!! – Max Aug 12 '15 at 04:58
  • @Max No problem. Be sure to review the [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle#Browser_compatibility) if that's a concern. – Marty Aug 12 '15 at 04:59