Skip to content

Instantly share code, notes, and snippets.

@mpouncy-netpulse
Forked from peteboere/jquery.alterclass.js
Last active January 11, 2018 19:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpouncy-netpulse/7811564 to your computer and use it in GitHub Desktop.
Save mpouncy-netpulse/7811564 to your computer and use it in GitHub Desktop.
jQuery alterClass plugin: Remove element classes with wildcard matching. Optionally add classes.
/**
* jQuery alterClass plugin
*
* Remove element classes with wildcard matching. Optionally add classes:
* $( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
*
* Copyright (c) 2011 Pete Boere (the-echoplex.net)
* Updated 2013 by Mike Pouncy (scrupl.es) - Condensed code, removed unneeded vars.
* Free under terms of the MIT license: http://www.opensource.org/licenses/mit-license.php
*
*/
;(function ( $ ) {
$.fn.alterClass = function jQueryAlterClass( removals, additions ) {
if ( removals.indexOf( '*' ) === -1 ) {
// Use native jQuery methods if there is no wild-card matching
this.removeClass( removals );
} else {
var pattern = new RegExp( '\\s'
+ removals
.replace( /\*/g, '[A-Za-z0-9-_]+' )
.split( ' ' )
.join( '\\s|\\s' )
+ '\\s', 'g' );
this.each( function forEachAlteredClass( i, it ) {
for ( var cn = ' ' + it.className + ' '; pattern.test( cn ); ) {
cn = cn.replace( pattern, ' ' );
}
it.className = $.trim( cn );
});
}
return( additions ? this.addClass( additions ) : this );
};
})( jQuery );
@mpouncy-netpulse
Copy link
Author

Condensed code, removed unneeded vars.

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