Skip to content

Instantly share code, notes, and snippets.

@peteboere
Created December 24, 2011 12:49
Star You must be signed in to star a gist
Save peteboere/1517285 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)
* Free under terms of the MIT license: http://www.opensource.org/licenses/mit-license.php
*
*/
(function ( $ ) {
$.fn.alterClass = function ( removals, additions ) {
var self = this;
if ( removals.indexOf( '*' ) === -1 ) {
// Use native jQuery methods if there is no wildcard matching
self.removeClass( removals );
return !additions ? self : self.addClass( additions );
}
var patt = new RegExp( '\\s' +
removals.
replace( /\*/g, '[A-Za-z0-9-_]+' ).
split( ' ' ).
join( '\\s|\\s' ) +
'\\s', 'g' );
self.each( function ( i, it ) {
var cn = ' ' + it.className + ' ';
while ( patt.test( cn ) ) {
cn = cn.replace( patt, ' ' );
}
it.className = $.trim( cn );
});
return !additions ? self : self.addClass( additions );
};
})( jQuery );
@jonathansayag
Copy link

Thanks for the code, very helpful for me !

@arthurhamon
Copy link

Great plugin it should be implement in jquery 1.12 or 2.2 !

@fadonascimento
Copy link

Good work!

@bonny
Copy link

bonny commented Apr 9, 2015

Great function – thanks a lot.

It also works with Zepto. Just pass in Zepto instead of jQuery and it just works.

@benzinkanister79
Copy link

Great Work! Thanks a lot ;)

@danyj
Copy link

danyj commented Nov 1, 2015

πŸ’―

@cdillon
Copy link

cdillon commented Dec 14, 2015

Very nice! Thanks a ton!

@cyberfly999
Copy link

Wonderful, thank you very much!

@tcomert
Copy link

tcomert commented Mar 21, 2016

Very useful, thanks

@anandbhaskaran
Copy link

Good work :)

@anand9
Copy link

anand9 commented May 19, 2016

thanks a lot.. πŸ‘

@timothyleerussell
Copy link

Nice. Very handy. +1

@xD3CODER
Copy link

Nice ! thanks a lot

@AreCoca25
Copy link

Nice! Thanks +1

@ponsakthianand
Copy link

Saved my time... Thank you!

@ztg-zlu
Copy link

ztg-zlu commented May 15, 2020

ζ­£ζ˜―ζˆ‘ιœ€θ¦ηš„

@Sasino97
Copy link

Saved a lot of my time, thanks 😍

@MohammedNuru
Copy link

MohammedNuru commented Jul 26, 2021

Great work man. and simple yet fast solution. Thanks! πŸ‘

@iamshareque
Copy link

thanks πŸ‘

@JyteCeo
Copy link

JyteCeo commented Sep 12, 2022

This is nice bro .. thanks

@Daniel-FDS
Copy link

Daniel-FDS commented Nov 6, 2023

This works beautifully... thank you very much, I truly appreciate it. πŸ™πŸΌ

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