Scripting Styles

The crux of DHTML is the ability to use JavaScript to dynamically change the style attributes applied to individual elements within a document. The DOM Level 2 standard defines an API that makes this quite easy to do. In Chapter 17, we saw how to use the DOM API to obtain references to document elements either by tag name or ID or by recursively traversing the entire document. Once you’ve obtained a reference to the element whose styles you want to manipulate, you use the element’s style property to obtain a CSS2Properties object for that document element. This JavaScript object has JavaScript properties corresponding to each of the CSS1 and CSS2 style attributes. Setting these properties has the same effect as setting the corresponding styles in a style attribute on the element. Reading these properties returns the CSS attribute value, if any, that was set in the style attribute of the element. It is important to understand that the CSS2Properties object you obtain with the style property of an element specifies only the inline styles of the element. You cannot use the properties of the CSS2Properties object to obtain information about the style-sheet styles that apply to the element. By setting properties on this object, you are defining inline styles that effectively override style-sheet styles.

Consider the following script, for example. It finds all <img> elements in the document and loops through them looking for ones that appear (based on their size) ...

Get JavaScript: The Definitive Guide, Fourth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.