Skip to Content
Web Design in a Nutshell, 3rd Edition
book

Web Design in a Nutshell, 3rd Edition

by Jennifer Robbins
February 2006
Intermediate to advanced
826 pages
63h 42m
English
O'Reilly Media, Inc.
Content preview from Web Design in a Nutshell, 3rd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Beginning Responsive Web Design with HTML5 and CSS3

Beginning Responsive Web Design with HTML5 and CSS3

Jonathan Fielding

Publisher Resources

ISBN: 0596009879Errata Page