YUI Library Examples: Dom Collection: Using removeClass

Dom Collection: Using removeClass

Clicking the button will use Dom's removeClass method to remove the class baz from the element.

foo

Using removeClass

removeClass, part of the YUI Dom Collection, makes it easy to remove a given className from an element.

To illustrate the use of removeClass, we'll create a <div> called foo with the classNames of bar and baz. When the button is clicked, we will remove the className baz from the element.

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

1<div id="foo" class="bar baz">foo</div> 
2<button id="demo-run">run</button> 
view plain | print | ?

Now we will define the function that removes the class baz from the foo element. The first argument of the removeClass method is either the ID of an HTMLElement, or an actual HTMLElement object. The second is the className to be removed.

1<script type="text/javascript"
2    var removeClass = function() { 
3        YAHOO.util.Dom.removeClass('foo''baz'); 
4        alert(YAHOO.util.Dom.get('foo').className); 
5    }; 
6</script> 
view plain | print | ?

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

1<script type="text/javascript"
2    YAHOO.util.Event.on('demo-run''click', testClass); 
3</script> 
view plain | print | ?

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

YUI Logger Output:

Logger Console

INFO67ms (+1) 6:01:54 PM:

Dom

isAncestor returning true

INFO66ms (+0) 6:01:54 PM:

Dom

addClass adding yui-link-button

INFO66ms (+0) 6:01:54 PM:

Dom

hasClass returning false

INFO66ms (+0) 6:01:54 PM:

Dom

addClass adding yui-button

INFO66ms (+1) 6:01:54 PM:

Dom

hasClass returning false

INFO65ms (+1) 6:01:54 PM:

Dom

getElementsBy returning

INFO64ms (+0) 6:01:54 PM:

Dom

setStyle setting visibility to visible

INFO64ms (+2) 6:01:54 PM:

Dom

setStyle setting height to auto

INFO62ms (+53) 6:01:54 PM:

LogReader instance0

LogReader initialized

INFO9ms (+0) 6:01:54 PM:

Dom

addClass adding yui-log

INFO9ms (+7) 6:01:54 PM:

Dom

hasClass returning false

INFO2ms (+2) 6:01:54 PM:

example

The example has finished loading; as you interact with it, you'll see log messages appearing here.

INFO0ms (+0) 6:01:54 PM:

global

Logger initialized

Note: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.

Reload with logging
and debugging disabled.

More Dom Collection Resources:

Copyright © 2008 Yahoo! Inc. All rights reserved.

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