Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 );
@anand9
Copy link

anand9 commented May 19, 2016

thanks a lot.. 👍

@timothyleerussell
Copy link

timothyleerussell commented Jul 16, 2016

Nice. Very handy. +1

@xD3CODER
Copy link

xD3CODER commented Jan 22, 2017

Nice ! thanks a lot

@AreCoca25
Copy link

AreCoca25 commented Mar 6, 2018

Nice! Thanks +1

@ponsakthianand
Copy link

ponsakthianand commented Jan 12, 2020

Saved my time... Thank you!

@ztg-zlu
Copy link

ztg-zlu commented May 15, 2020

正是我需要的

@SaSiNO97
Copy link

SaSiNO97 commented Dec 11, 2020

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

iamshareque commented Apr 16, 2022

thanks 👍

@JyteCeo
Copy link

JyteCeo commented Sep 12, 2022

This is nice bro .. thanks

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