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(title, null);

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

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.