Section 27.5. Working with Style


27.5. 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 the head of the page and then use getAttribute( ) to find the style sheet you want to disable/enable. Setting the disabled property of a style sheet's link element to true will disable it. Setting it to false will enable it again.

27.5.1. Resources

Before we dive into some real-world examples, here are a few great resources to help you on your way:

  • WaSP DOM Scripting Task Force (domscripting.webstandards.org)

  • DOM Scripting: Web Design with JavaScript and the Document Object Model by Jeremy Keith (Friends of Ed)

  • DHTML Utopia: Modern Web Design Using JavaScript & DOM by Stuart Langridge (SitePoint)




Web Design in a Nutshell
Web Design in a Nutshell: A Desktop Quick Reference (In a Nutshell (OReilly))
ISBN: 0596009879
EAN: 2147483647
Year: 2006
Pages: 325

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net