Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery removeClass() to remove all classes but one

Okay, I've got an interesting one (well, interesting to me, anyway :) ).

I've got a situation where I have a div with a static class value, but it also can have a single, "secondary class" assigned that is dynamic. When the user makes a selection, any existing secondary class needs to be removed and the new class added.

Ignoring using an id value (standards for the project use the class . . . can't be changed), is there an elegant way to simply ignore the first class and remove whatever other class is there, before adding the new one?

Example Starting HTML:

<div class="staticClass dynaClass1" />

Example JS:

function updateClass(newSecondaryClass) {
    $(".staticClass") . . . **** remove any class besides "staticClass" ****
    $(".staticClass").addClass(newSecondaryClass);
}

If the function is called using updateClass("dynaClass2");, the resulting HTML should be:

<div class="staticClass dynaClass2" />

I can think of ways of doing it involving just removing all classes using removeClass(); and adding "staticClass" back in when adding the new class, or using attr("class", "staticClass " + newSecondaryClass);, but I'm wondering if there isn't a way to handle it without having to touch the static class at all?

In the end, I guess this is an academic question, more than anything . . . just seems like it's something that should be doable, but I don't know how to do it. :D

like image 728
talemyn Avatar asked Jan 14 '13 16:01

talemyn


People also ask

How do I get rid of all classes?

To remove all classes, use the removeClass() method with no parameters. This will remove all of the item's classes.

Can you remove a class with jQuery?

As of jQuery 1.4, the . removeClass() method allows us to indicate the class to be removed by passing in a function.

How can I replace one class with another in jQuery?

To replace a class with another class, you can remove the old class using jQuery's . removeClass() method and then add the new class using jQuery's . addClass() method.


2 Answers

You can remove all classes and add the one you want to leave:

$(".staticClass").removeClass().addClass('staticClass');

Calling removeClass() without a parameter removes all classes.

If you don't want to do that then you can simply modify the class attribute:

$(".staticClass").attr('class', 'staticClass');
like image 162
Konstantin Dinev Avatar answered Nov 08 '22 01:11

Konstantin Dinev


You can pass a function to remove class, which returns all but the static Classes:

$('.staticClass').removeClass(function(index, klass) { 
  return klass.replace(/(^|\s)+staticClass\s+/, ''); 
})

This is returning all the classes that are on the object, without the static one, and therefore removes all classes but the static one.

like image 27
Beat Richartz Avatar answered Nov 08 '22 01:11

Beat Richartz