Skip to content

Instantly share code, notes, and snippets.

@jakubp
Created June 6, 2012 12:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jakubp/2881585 to your computer and use it in GitHub Desktop.
Save jakubp/2881585 to your computer and use it in GitHub Desktop.
jQuery plugin to remove classes with given prefix
// Remove classes that have given prefix
// Example:
// You have an element with classes "apple juiceSmall juiceBig banana"
// You run:
// $elem.removeClassPrefix('juice');
// The resulting classes are "apple banana"
// NOTE: discussion of implementation techniques for this, including why simple RegExp with word boundaries isn't correct:
// http://stackoverflow.com/questions/57812/jquery-remove-all-classes-that-begin-with-a-certain-string#comment14232343_58533
(function ( $ ) {
$.fn.removeClassPrefix = function (prefix) {
this.each( function ( i, it ) {
var classes = it.className.split(" ").map(function (item) {
return item.indexOf(prefix) === 0 ? "" : item;
});
it.className = classes.join(" ");
});
return this;
}
})( jQuery );
@drywall
Copy link

drywall commented Feb 11, 2013

This is awesome and does what I need.... I did notice that in Safari at least, for some reason extra spaces were being appended in the string as the class changed. I changed line 18 to:

it.className = $.trim(classes.join(" "));

And that seems to have resolved the issue.

@iaroslavshvets
Copy link

I am almost sure, that problem with IE occured because of "each" function, earlier versions of IE doesn't support it. The workaround is to use normalized jQuery $.each instead. Like $.each(this,function(i, it){})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment