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")

Comments

Anonymous at 13 Mar, 2007 08:36
Article obviously served the purpose!!!
Reply to this.
Anonymous at 09 Oct, 2007 11:28
exactly what i was looking for and more!
Reply to this.
Anonymous at 25 Feb, 2008 05:29
Just what I needed. Great!
Reply to this.
Anonymous at 16 Apr, 2008 01:34
This is great. I needed it on one page and didn't want to download an entire library to do these three functions. Lean and Clean.
Reply to this.
Comment


Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.