Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery removeClass wildcard

Tags:

html

jquery

Is there any easy way to remove all classes matching, for example,

color-*

so if I have an element:

<div id="hello" class="color-red color-brown foo bar"></div>

after removing, it would be

<div id="hello" class="foo bar"></div>

Thanks!

like image 871
atp Avatar asked Apr 15 '10 10:04

atp


3 Answers

The removeClass function takes a function argument since jQuery 1.4.

$("#hello").removeClass (function (index, className) {
    return (className.match (/(^|\s)color-\S+/g) || []).join(' ');
});

Live example: http://jsfiddle.net/xa9xS/1409/

like image 96
jimmystormig Avatar answered Nov 06 '22 03:11

jimmystormig


$('div').attr('class', function(i, c){
    return c.replace(/(^|\s)color-\S+/g, '');
});
like image 31
Kobi Avatar answered Nov 06 '22 02:11

Kobi


I've written a plugin that does this called alterClass – Remove element classes with wildcard matching. Optionally add classes: https://gist.github.com/1517285

$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
like image 23
Pete B Avatar answered Nov 06 '22 04:11

Pete B