Yahoo! Developer Network Home - Help

YDN Site Search

# YUI Library Examples: Dom Collection: Using hasClass

# Dom Collection: Using hasClass

Clicking the button will use Dom's `hasClass` method to test if the element has the class `baz` applied.

View example in new window.

foo

## Using hasClass

`hasClass`, part of the YUI Dom Collection, makes it easy to test whether a given className is present on an element.

To illustrate the use of `hasClass`, we'll create a `<div>` called `foo` with the className of `bar` and `baz`. When the button is clicked, we will test whether the `className` `baz` is present.

Add some markup for the demo element:

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

Now we will define the function that tests whether `foo` has the `className` `baz` applied. The first argument of the `hasClass` method is either the ID of an HTMLElement, or an actual HTMLElement object. The second is the `className` we are testing for. The `hasClass` method returns `true` or `false`, depending on whether the `className` exists on the element. <script type="text/javascript"> var testClass = function() { alert(YAHOO.util.Dom.hasClass('foo', 'baz')); }; </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', testClass); </script>

This is a simple example of how to use the `YAHOO.util.Dom.hasClass` method. One of the benefits of this method is that it works regardless of how many `className`s are present in the class attribute.

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

### More Dom Collection Resources:

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

Copyright © 2007 Yahoo! Inc. All rights reserved.

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