Working with Style

Once you’ve mastered the art of structural manipulation with the DOM, you should turn your focus to working with Cascading Style Sheets. The DOM allows access to add, modify, and remove CSS styles. DOM-based CSS manipulation works just like applying inline style using the style attribute.

It is possible, in most modern browsers, to use the setAttribute( ) method to assign a value to the style attribute of an element:

var div = document.getElementById( 'content' );
div.setAttribute( 'style', 'color: #f00; font-weight: bold;' );

Unfortunately, Internet Explorer (at least through Version 6) does not support this method of style application. Thankfully, there is an HTML DOM convention that is available consistently in all browsers: the style property.

div.style.color = '#f00';
div.style.fontWeight = 'bold';

Although not nearly as efficient as using setAttribute( ), this convention does allow granular control of styles.

The style property can be used to get or set style values.

var old_color   = div.style.color; // red
div.style.color = '#f90';          // orange

Individual CSS properties are available as properties of the style property. Hyphenated property names are shortened to camel case to avoid conflict with the subtraction operator (-) in JavaScript. For example, font-weight becomes fontWeight, border-left-width becomes borderLeftWidth, and so on.

The DOM also gives you the ability to disable and enable entire style sheets. To do this, you simply tap into the link elements within ...

Get Web Design in a Nutshell, 3rd 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.