Return to Snippet

Revision: 56654
at April 7, 2012 05:48 by ChristianOttinger


Initial Code
Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}
Element.prototype.addClass = function $_addC(clas){
	if(this.className && this.className !== '') { // it already has at least one class
		if(!this.hasClass(clas)){
			this.className = this.className+' '+clas;
		}
	} else { // it doesnt have any classes yet
		this.className = clas;
	}
}
Element.prototype.hasClass = function $_has(clas){
	if((this.className.split(' ')).contains(clas)) return true;
	return false;
}
Element.prototype.countClasses = function $_count(){
	if(!this.className) return 0; 
	if(this.className.replace(' ') == this.className) return 1;
	var listOf = this.className.split(' ');
	return listOf.length;
}
Element.prototype.removeClass = function $_remove(clas){
	if(this.hasClass(clas)){ // make sure it has the class we want to remove
		if(this.countClasses() == 1) this.className = '';
		else {
			var reg = new RegExp('(\\s|^)'+clas+'(\\s|$)');
			this.className=this.className.replace(reg,' ');
		}
	}
}
Element.prototype.toggleClass = function $_toggle(clas1){
	if(this.hasClass(clas1)) this.removeClass(clas1);
	else this.addClass(clas1);
}

Initial URL


Initial Description
Element.prototype functions to manipulate element classes.

Initial Title
Class Manipulation

Initial Tags
class

Initial Language
JavaScript