tags:

views:

65

answers:

3

Hi I have an li element that will have something along the lines of this for a declaration

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

And I can dynamically change the color of the module by adding on classes (That are provided dynamically through DB calls) the end result being

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

or

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

Well I am fine with changing the color by adding on a new module-WHATEVER class but what I would like to do is remove any class that matches module-XXXX so it starts with a clean slate and then add on the class module-crimson.

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

EDIT:

I basically need the method of doing a clean sweep on any module- class:

Before Execution

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

After Clean Sweep

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

Then Add Class and Final Result

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

Thanks.

-Seth

+6  A: 

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');

});

ouput this:

<li class="module ui-helper-fix"> 
aSeptik
This is close, but what I would like to do is basically everytime I try to add a new color class (module-green, module-default, etc.) I do a clean sweep of that elements classes for any matching "module-" classes.
Seth Duncan
so you basicaly want remove all the module-xxx and leave just module! right!?
aSeptik
Yes, if you see my edit above, it may be more clear now.
Seth Duncan
Worked like a charm, Thank you very much!
Seth Duncan
you welcome bro! ;-)
aSeptik
+1  A: 

Here:

var newClass = "module-green";
$("li").attr("class","module ui-helper-fix").addClass(newClass);
David Murdoch
This would technically work, however there are certain occasions where it wouldn't just be module and ui-helper-fix included in the class list. But Nevertheless +1
Seth Duncan
A: 
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');
    })
});
artlung