Removing all match classes in jQuery

Hi I have an li element that will have something in the lines of this to declare

<li class="module ui-helper-fix">

      

And I can dynamically change the color of the module by adding to the classes (which are provided dynamically via DB calls), the end result

<li class="module ui-helper-fix module-green">

      

or

<li class="module ui-helper-fix module-default"> 

      

It's good that I change the color well by adding a new class-WHATEVER, but what I would like to do is remove any class that matches module-XXXX, so it starts with a clean slate and then adds the class module -crimson.

So how do I first remove all classes that match module-xxx? With that in mind, I don't want to remove the base module class.

EDIT:

I basically need a method to do a clean sweep on any modular class:

Before doing

<li class="module ui-helper-fix module-default">

      

After Clean Sweep

<li class="module ui-helper-fix">

      

Then add the class and final result

<li class="module ui-helper-fix module-green">

      

Thanks.

-Seth

+2


a source to share


4 answers


UPDATED

DEMO: http://jsbin.com/onoxa/7

DEMO 2: http://jsbin.com/onoxa/8

$(function() {
    $("li").each(function(e) {     
    var classes = this.className.replace(/module-\w+/gi, '' );
        $(this).attr('class', classes);
    });
});​

      




$("li").each(function(e) {
    var classes = this.className.replace(/module-\w+/gi, '');
    $(this).attr('class', classes + ' module-green');

});

      

output this:

<li class="module ui-helper-fix"> 

      

+6


a source


Use this:



var newClass = "module-green";
$("li").attr("class","module ui-helper-fix").addClass(newClass);

      

+1


a source


function changeModule(selector, module_name) {
    var that = selector;
    var classes = $(selector).attr('class').split(' ');
    $.each(classes, function(index, thisClass){
        if (thisClass.indexOf('module-') !== -1) {
            $(that).removeClass(classes[index])
        }
    });
    $(that).addClass(module_name);
}

jQuery(document).ready(function(){ 
    $('li').click(function(){
        changeModule(this, 'module-green');
    })
});

      

0


a source


Maybe this is just an old post, but as of jQuery 1.4 you can provide a match function.removeClass()

Example: http://jsfiddle.net/drzaus/MJdRy/

$('.module')
    .removeClass(function(i,c) {
        return c.match(/module-\w+/gi).join(' ');
    })
    .addClass('module-green');

      

based on answer here

It looks clunkier than the accepted answer , but it's the "jQuery way".

0


a source







All Articles