YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: Dom Collection: Using addClass

# Dom Collection: Using addClass

Clicking the button will use Dom's `addClass` method to add the class `baz` to the element.

View example in new window.

foo

## Using addClass

addClass, part of the YUI Dom Collection, makes it easy to add a given className to an element.

To illustrate the use of addClass, we'll create a `<div>` called `foo` with the className of `bar`. When the button is clicked, we will add the className `baz` to the element.

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

<div id="foo" class="bar">foo</div> <button id="demo-run">run</button>

Now we will define the function that adds the class `baz` to the `foo` element. The first argument of the `addClass` method is either the ID of an HTMLElement, or an actual HTMLElement object. The second is the className to be added. <script type="text/javascript"> var addClass = function() { YAHOO.util.Dom.addClass('foo', 'baz'); alert(YAHOO.util.Dom.get('foo').className); }; </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', addClass); </script>

This is a simple example of how to use the Dom.addClass method. One of the benefits of this method is that it works regardless of how many classNames are present in the class attribute.

## 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: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.

Reload with logging
and debugging disabled.

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