Simplest Classname Switcher

On 5-29-2007, in Coding, JavaScript, by Alex

Simplest JS function to add/remove custom classname with carrying about another classes.
just to remember.

function toggleClassName(obj,sClassName,switcher){
	if(switcher){
		if(obj.className.indexOf(sClassName)==-1)
			obj.className=obj.className + ' ' + sClassName;
	}else{
		var re = new RegExp(sClassName,'g');
		obj.className=obj.className.replace(re,'');
	}
}

sapienti sat

 

3 Responses to Simplest Classname Switcher

  1. Lynn says:

    toggleClassName(div, ‘test’, false)

    Oooops…

  2. Lynn says:

    function toggleClassName(obj,sClassName,switcher){
    var re = new RegExp('\b'+sClassName+'\b','g');
    if(switcher){
    if(!obj.className.match(re))
    obj.className=obj.className + ' ' + sClassName;
    }else{
    obj.className=obj.className.replace(re,'');
    }
    }

  3. Alex says:

    Good idea, thanks a lot! 🙂