Class Manipulation using JavaScript

As you may know, JavaScript is for behaviour and CSS is for presentation. But often we use the 'style' property of an element to change the apperance of an element. A better way of approching the problem is to change the classname of the element in question and define the class in the CSS file.

Example

Old Method

error_message.style.color="red";

Using Classes

error_message.className = 'error-message';

If 'error_message' already have other classes

error_message.className += ' error-message';

This way, all the presentation elements will be kept in one place - the CSS file.

I made three small functions to manipulate the classnames of DOM elements easily. These were used in the Live Validation script.


function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}

Libraries

Of course, this can easily be done using your favorite library...

Prototype

Element("element").ClassNames.add("ClassName")
Element("element").ClassNames.remove("ClassName")
Element("element").ClassNames.set("ClassName")

Documenation

jQuery

$("element").addClass("ClassName")
$("element").removeClass("ClassName")

YUI

YAHOO.util.Dom.hasClass(element,"ClassName")
YAHOO.util.Dom.addClass(element,"ClassName")
YAHOO.util.Dom.removeClass(element,"ClassName")
blog comments powered by Disqus