YUI Library Examples: Dom Collection: Using getStyle

Dom Collection: Using getStyle

Clicking the button will use Dom's getStyle method to get the background color of the red element and pass it to the setStyle method, which will set the blue element's background to the same color.

Using getStyle

getStyle, part of the YUI Dom Collection, makes it easy to get an element's position relative to the document.

To illustrate the use of getStyle, we'll create a <div> called foo and a <div> called bar. When the button is clicked, the background color from bar will be applied to foo.

Add some simple CSS rules and markup for the demo element and a button to trigger the demo:

Now we will define the function that sets the background color of foo to the background color of bar. The first argument of the getStyle method is either the ID of an HTMLElement, or an actual HTMLElement object. The second is the style property that we wish to retrieve. The getStyle method returns the element&spos;s current value for that property.

To trigger the demo, we will use the YUI Event Utility's on method to listen for clicks on the button.

This is a simple example of how to use the YAHOO.util.Dom.getStyle method. One of the benefits of this method is that it can retrieve either inline styles or styles set in a stylesheet. Browsers have different methods for retrieveing styles from a stylesheet, but the getStyle method normalizes these for you.

YUI Logger Output:

Note: Logging and debugging is currently turned off for this example.

Reload with logging
and debugging enabled.

More Dom Collection Resources:

Copyright © 2007 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings