Querying Computed Styles

The style property of an element is that element’s inline style. It overrides all stylesheets, and it is the perfect place to set CSS properties to change the visual appearance of an element. It is not, however, generally useful for querying the styles that actually apply to an element. For that, you want the computed style. The computed style for an element is the set of property values that the browser derives (or computes) from the inline style plus all applicable style rules in all linked stylesheets: it is the set of properties actually used to display the element. Like inline styles, computed styles are represented with a CSSStyleDeclaration object. Unlike inline styles, however, computed styles are read-only. You can’t set these styles, but the computed CSSStyleDeclaration object for an element lets you determine exactly what style property values the browser used when rendering that element.

Obtain the computed style for an element with the getComputedStyle() method of the Window object. The first argument to this method is the element whose computed style is desired. The second argument is required and is usually null or the empty string, but it can also be a string that names a CSS pseudoelement, such as “:before”, “:after”, “:first-line”, or “:first-letter”:

var title = document.getElementById("section1title");
var titlestyles = window.getComputedStyle(element, null);

The return value of getComputedStyle() is a CSSStyleDeclaration object that represents ...

Get JavaScript: The Definitive Guide, 6th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.