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
You can remove all classes and add the one you want to leave:
Calling
removeClass()
without a parameter removes all classes.If you don't want to do that then you can simply modify the class attribute:
All of your classes are manipulated by calling the Javascript DOM
element.className
, so basically jQuery'saddClass
just replaces that string. You can see that in the Github source.Which all means that if you call
The
element.className
is replaced anyway, but with the new class included. ( this means that yourstaticClass
is actually touched :)When you call
you will replace that string twice and there is no problem doing that.
You can pass a function to remove class, which returns all but the static Classes:
This is returning all the classes that are on the object, without the static one, and therefore removes all classes but the static one.
Pass a function to
.removeClass()
A revision of Beat Richartz's answer on this page.
Note: I tried to post this as an edit and it was rejected. The concept is identical, with an improved RegEx.
Improved RegEx provides word-boundary matching with multiple classes
Before:
After:
Try it: http://jsfiddle.net/gfullam/52eeK/3/
Try it as a jQuery plugin: http://jsfiddle.net/gfullam/52eeK/5/
FWIW: This method is necessary when you don't want to replace the existing classes with other classes as in
.attr('class', '<final list of classes>')
, but instead just want to remove those that don't match a list of classes.You can set it's required classes using the
.attr()
function. So:This will replace any classes that were originally there, and add the new ones.