Combining jQuery’s addClass() + removeClass() attributes

A few times I’ve been in a situation where I’ve been working on a web application, or creating some custom form validation and for whatever reason I’ve needed to add and remove multiple CSS classes from a selector. Obviously jQuery has .addClass() and .removeClass() methods, both of which are invaluable in pretty much any jQuery project, but as a person who likes to keep code as concise as possible I still found it a little frustrating that I was having to add both attributes every time.

Enter $.classer()
Classer is a bit of very simple plugin code which basically just combines both .addClass() and .removeClass() into a single method. This might sound like a slightly redundant bit of functionality, ho

The Code
This can be pasted at the top or bottom of any JavaScript file in your project so long as it is subsequent to the loading of jQuery:

$.fn.classer = function (on, off) {
    if (typeof off != "undefined") {

Rather than adding separate .addClass() and .removeClass() attributes to a selector, .classer() allows you to combine the two into separate parameters of the same function:

$("input").focus(function() {
	$(this).classer("active","complete error");
}).blur(function() {
	if (validateInput($(this))) {
		$(this).classer("complete","active error");
	} else {
		$(this).classer("error","active complete");
Tweet about this on TwitterShare on Facebook0Share on Google+0Share on LinkedIn0

Leave a reply