Skip to content

Instantly share code, notes, and snippets.

@wolever
Created January 13, 2014 04:51
Show Gist options
  • Save wolever/8394924 to your computer and use it in GitHub Desktop.
Save wolever/8394924 to your computer and use it in GitHub Desktop.
jQuery plugin to toggle an element's classes based on a prefix.
/**
* Toggles the CSS classes of an element based on a prefix::
* > elems = $(".status")
* > elems
* [<div class="status status-active">, <div class="status status-pending">]
* > elems.toggleClassPrefix("status-", "status-pending")
* > elems
* [<div class="status status-pending">, <div class="status status-pending">]
*/
$.fn.toggleClassPrefix = function(prefix, toAdd) {
$(this).each(function() {
var newClass = $.grep(this.classList, function(cls) {
return cls.indexOf(prefix) != 0;
});
newClass.push(toAdd);
this.className = newClass.join(" ");
});
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment