views:

43

answers:

3

Is there any better way to rewrite this ?

$('element').removeClass('class-1').removeClass('class-2').removeClass('class-3').removeClass('class-5') ...
to .removeClass('class-105')
:)

i want to remove all class-(n) classes

Thanks

A: 

Get the classes of the element, process it as a string, and put it back:

$('element').attr(
  'className',
  $('element').attr('className').replace(/\bclass-\d+\b/g, '')
);
Guffa
The selector would be off per element though, I'd write it like this: `$('element').attr('className', function(i, c) { return c.replace(/\bclass-\d+\b/g, ''); });​`
Nick Craver
thank you Guffa, it works :)
klezer
@Nick Craver: Yes, that would be useful if you need to apply it to seveal elements. :)
Guffa
A: 

Doing it in a better way using css selector, [type*=value]

$(function() {
    var i = 0;
    while( ++i <= 105) {
        $('b').addClass('class-'+ i);
    }
  var clas = '';
  var arey =[]
    $('input[type=button]').click(function() {  
        clas = $('b').attr('class');
        arey = clas.match(/class-\d{1,3}/g);
        $.each(arey, function(i, e) {
            $('b').removeClass(e);      
        });
    });
}); 

Edit :

Demo : http://jsbin.com/opebu4/2

Ninja Dude
This would assume that each element has only one class with `class-`, and that they appear in perfect numerical order in the document. I don't think that's the point of the question.
patrick dw
@patrick, yes you're right. is there a better way doing this using the same selector ? I'm just curious to know
Ninja Dude
@Nick Cravers answer (in the comment under the Accepted answer) is probably the best way to go, though it requires jQuery 1.4 or later. I'll post an answer that would work for pre-jQuery 1.4.
patrick dw
@patrick please Check my updated answer
Ninja Dude
Yes, that would seem to work if you have only one element. If there's more than one, you would want to place your code in an `.each()` and operate on each element individually. A little complicated, but should work. :o)
patrick dw
A: 

...or you can use a starts-with selector if you know the possible class names you'd like to remove. The nasty part of the task is the sheer number of classes to look for...

$(document).ready(function () {
     var classesOfInterest = '';
     for(var i = 1; i<=105; i++)
        classesOfInterest += ' ' + 'class-' + i;
     alert(classesOfInterest);
     $("[class^='class-']").removeClass(classesOfInterest);
  });
Tahbaza