2

Possible Duplicate:
Remove all classes that begin with a certain string

I have a script which adds one of six classes randomly to the body. The classes are numbered between 1 and 6, like this:

theme-1 to theme-6.

I need a clean way to remove all of them. Right now I have this:

$('body').removeClass('theme-1');
$('body').removeClass('theme-2');
$('body').removeClass('theme-3');
$('body').removeClass('theme-4');
$('body').removeClass('theme-5');
$('body').removeClass('theme-6');

But it's kind of clunky right? Is there a way I can say "remove any classes between theme-1 to theme-6"?

Community
  • 1
  • 1
shrewdbeans
  • 11,971
  • 23
  • 69
  • 115

6 Answers6

3

You can use the loop index to generate class names.

classes = ""
for(i=1; i < 7; i++)
   classes += 'theme-' + i + " ";
$('body').removeClass(classes);
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Adil
  • 146,340
  • 25
  • 209
  • 204
1

You could combine it all in to one line:

$('body').removeClass('theme-1 theme-2 theme-3 theme-4 theme-5 theme-6');

Or use a loop, though if the classes are always between 1 and 6 the loop seems like overkill personally.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
0

You could clear them in a loop, which is, at least, a little cleaner.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
0

If you don't know how many of those you might have, you should use a regex:

document.body.className = document.body.className.replace(/(^| )theme-\d+( |$)/g, ' ');

If you want to stay within the jQuery API, use this:

$('body').attr('class', function (i, className) {
    return className.replace(/(^| )theme-\d+( |$)/g, ' ');
});

If you don't have any other classes on the body, you can remove them all in one fell swoop:

$('body').removeClass();
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
0

Answer posted here. The code from Pat is as follows:

$('body')[0].className.replace(/\theme-.*?\b/g, '');

But this answer from Prestaul looks good as well. Use this function:

function removeClassByPrefix(el, prefix) {
    var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
    el.className = el.className.replace(regx, '');
    return el;
}
Community
  • 1
  • 1
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
0
$('body').removeClass('theme-1 theme-2 theme-3 theme-4 theme-5 theme-6');

http://jsfiddle.net/Yms5M/

Roman Liutikov
  • 1,338
  • 10
  • 17