YUI Library Home

Site Search (YDN & YUIBlog):

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

View example in new window.

## Using getStyle

`getStyle`, part of the YUI Dom Collection, makes it easy to get the value of style properties from HTMLElements.

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:

<style type="text/css"> #foo { background-color:#00f; height:10px; width:10px; } #bar { width:100px; height:100px; background-color:#f00; margin:0 0 1em 100px; } </style> <div id="foo"></div> <div id="bar"></div> <button id="demo-run">run</button>

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's current value for that property. <script type="text/javascript"> var setBgColor = function() { var bgcolor = YAHOO.util.Dom.getStyle('bar', 'backgroundColor'); YAHOO.util.Dom.setStyle('foo', 'backgroundColor', bgcolor); }; </script>

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

<script type="text/javascript"> YAHOO.util.Event.on('demo-run', 'click', setBgColor); </script>

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.

## Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

### YUI Logger Output:

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

Reload with logging
and debugging enabled.

### Dom Collection Examples:

- Using setXY
- Using getXY
- Using setStyle
- Using getStyle
- Using hasClass
- Using addClass
- Using removeClass
- Using getElementsByClassName
- Exploring the Dom Collection's API

### More Dom Collection Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2010 Yahoo! Inc. All rights reserved.

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