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('.example').toggleClass('redText');
	});
	Y.one('#changeclass').on('click', function(e) {
		Y.one('.example').addClass('greenText');
	});
	Y.one('#removeclass').on('click', function(e) {
		if (Y.one('.example').hasClass('redText')) {
			Y.one('.example').removeClass('redText');
		}
		if (Y.one('.example').hasClass('greenText')) {
			Y.one('.example').removeClass('greenText');
		}
	});
});

HTML used in the example:


Example- Dynamically assigning class, toggle class etc
<div class="example" style="width:200px;height:100px;">
	.addClass('foo')
	.removeClass('foo')
	.toggleClass('foo')
	.hasClass('foo')
	.replaceClass('foo', 'bar')
</div>
<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:


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

Hope this YUI3 node tutorial has saved you some time!