Return to Snippet

Revision: 3624
at August 23, 2007 12:12 by skatan


Updated Code
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,' ');
	}
}

//call the functions
addClass(document.getElementById("test"), "test");
removeClass(document.getElementById("test"), "test")
if(hasClass(document.getElementById("test"), "test")){//do something};

Revision: 3623
at August 23, 2007 11:58 by skatan


Initial Code
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,' ');
     }
 }

Initial URL
http://www.openjs.com/scripts/dom/class_manipulation.php

Initial Description

                                

Initial Title
addClass, removeClass, hasClass

Initial Tags
javascript

Initial Language
JavaScript