YUI3 Tutorial: Working with Node – 2. Dynamically Add, Remove and Toggle CSS Class

Here is another post for . Here I am going to present examples for adding Class, removing class and toggle css class dynamically using YUI.

YUI3 provides .addClass('foo'), .removeClass('foo'), .toggleClass('foo'), .hasClass('foo') and .replaceClass('foo', 'bar') for dynamically working with class on an element.

Javascript used in the example:

YUI().use('node', function(Y) {
	Y.one('#toggleclass').on('click', function(e) {
	Y.one('#changeclass').on('click', function(e) {
	Y.one('#removeclass').on('click', function(e) {
		if (Y.one('.example').hasClass('redText')) {
		if (Y.one('.example').hasClass('greenText')) {

HTML used in the example:

Example- Dynamically assigning class, toggle class etc
<div class="example" style="width:200px;height:100px;">
	.replaceClass('foo', 'bar')
<button id="toggleclass">Toggle Class. Add Red text class and remove it on another click</button>
<button id="removeclass">Remove red and green text class</button>
<button id="changeclass">Change Class. Add Green text class.</button>

CSS used in the example:

.redText {color:red; font-size:16px;font-weight:bold;}
.greenText {color:green;font-size:22px;}

Hope this YUI3 node tutorial has saved you some time!