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 modu开发者_开发问答le 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
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">
Use this:
var newClass = "module-green";
$("li").attr("class","module ui-helper-fix").addClass(newClass);
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');
})
});
Maybe this is just an old post, but since jQuery 1.4 you can provide a matching function to .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".
精彩评论