Using CSS with the DOM

There are four ways to access CSS styles through JavaScript and the DOM. These include:

  1. the element object style
  2. the styleSheet object (member of the styleSheets array
  3. the rule (or cssRule) object (member of the rules/cssRules array)
  4. the style object.

style is the element representing the <style> tag in the document source. Generally speaking, we cannot read or write style properties through this element. A stylesheet can be embedded in a document with the <style> tag or linked through a link element. The styleSheets property (a property of the document object) returns an array of stylesheets objects currently visible throughout the document, either they are disabled or not. In this array there are the stylesheets defined by a <style> tag, or linked via the <link> tag.

For example, even though the style tag contains the rules of a stylesheet, this object is not a way to get access to a single rule, while this can be achieved through the styleSheet object. In fact, through this object we can enable or disable an entire stylesheet, access to the single rules (with the rules/cssRules array) and add or delete rules for a given stylesheet.

A CSS stylesheet is made up of rules which define how page elements must be displayed. The IE object model calls each rule a rule object, whereas the W3C DOM Level 2 calls it a cssRule object. Despite these incompatibilities, both objects share the basic names for properties.

We need array references to select a rule. For example, a reference to the first rule of the first stylesheet object in a document looks as follows:

var IERule = document.styleSheets[0].rules[0];
var W3CRule = document.styleSheets[0].cssRules[0];

The last object in this group is style. This object is where the actual style definitions take place and corresponds to the style attribute of every XHTML element. For example, to set the text color of an element whose ID attribute is "test" we can use the following syntax:

document.getElementById('test').style.color = 'blue';

This object is also a property of a rule/cssRule object. Therefore, when we need to modify the style of elements affected by a CSS rule, the style object is reached through a different path, but the object itself is treated as we've seen above:

// IE
document.styleSheets[0].rules[0].style.color = 'blue';

// W3C
document.styleSheets[0].cssRules[0].style.color = 'blue';

We're often concerned with the style object associated to a particular XHTML element. In fact, there are few examples where the manipulation of an entire stylesheet is required, usually when we want to enable or disable an entire stylesheet through JavaScript.

This entry was posted in , by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.