Other DOM APIs for Styles and Style Sheets

So far in this chapter, we’ve discussed a simple DOM API for working with CSS styles: every HTMLElement in a document has a style property that represents the inline style attributes of that element. The style property refers to a CSS2Properties object that defines a JavaScript property for each CSS style attribute defined by the CSS2 standard.

Although we’ve made extensive use of it, the CSS2Properties object is just one part of the DOM API for CSS.[69] This section provides a quick overview of the rest of the DOM API for working with CSS style sheets. Note, however, that at the time of this writing, much of the CSS API is not well supported by current (sixth-generation) browsers. You should test carefully before relying on any of the APIs described here.

Style Declarations

The CSS2Properties interface is a subinterface of CSSStyleDeclaration. Thus, the style property of each document element also implements the properties and methods of CSSStyleDeclaration. The methods include setProperty( ) and getPropertyValue( ), which you can use as an alternative to setting and querying the individual style properties of CSS2Properties. For example, these two lines of code accomplish the same thing:

element.style.fontFamily = "sans-serif";
element.style.setProperty("font-family", "sans-serif", "");

Other features of the CSSStyleDeclaration interface are the removeProperty( ) method, which deletes a named style, and the cssText property, which ...

Get JavaScript: The Definitive Guide, Fourth 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.