Clicking the button will use Dom's addClass
method to add the class baz
to the element.
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:
1 | <div id="foo" class="bar">foo</div> |
2 | <button id="demo-run">run</button> |
view plain | print | ? |
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.
1 | <script type="text/javascript"> |
2 | var addClass = function() { |
3 | YAHOO.util.Dom.addClass('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', addClass); |
3 | </script> |
view plain | print | ? |
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.
INFO39ms (+1) 9:52:16 PM:Dom
addClass adding yui-log
INFO38ms (+34) 9:52:16 PM:Dom
hasClass returning false
INFO4ms (+4) 9:52:16 PM:example
The example has finished loading; as you interact with it, you'll see log messages appearing here.
INFO0ms (+0) 9:52:16 PM:global
Logger initialized
Note: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.
Copyright © 2008 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings