Reputation: 101
how do i remove classes with jQuery?
I have this "template" i am working on and i want a "settings" box to the left where the user can change the "color scheme" of the navigation.
I have like 5-10 colors and i cant get it to work.
$(".color-orange").click(function () {
$("#nav").addClass("color-orange");
});
How can i then remove the class "color-orange" and add a new class if someone clicks on green?
Well i used this..
$(".color-green").click(function () {
$("#nav").removeClass("color-orange");
$("#nav").addClass("green");
});
But that just takes orange away. And will not work if you clicked another color.. Sorry for my english, and yes. Its my first time here :)
Kind Regards / Albin
Upvotes: 1
Views: 142
Reputation: 178421
How about this
$('[class^="color-"]').each(function() {
$("#nav").removeClass().addClass($(this).attr("class"));
}
or as xFortyFourx pointed out:
$('[class^="color-"]').each(function() {
$("#nav").attr("class",$(this).attr("class"));
}
Alternative - if I assume you have
.green { color:green; .... } /* for the nav */
.color-green { color:green; .... } /* for the settings */
you can do
$('[class^="color-"]').each(function() {
$("#nav").attr("class",$(this).attr("class").replace("color-",""));
}
Upvotes: 3
Reputation: 2984
The below code will simply overwrite existing classes to whatever you set (in this case "green").
$("#nav").attr("class", "green");
Since this has gained enough upvotes, I'll tell you why this is kind of better answer than the above one. The one with removeClass()
.
First, you get the required element, that is $("#nav")
.
Then, you call a property of JQuery, removeClass()
.
Then, you again call another property of JQuery, addClass()
.
In the solution I suggested:
First, you get the element, then call the propery attr()
, and that's it.
So, it's one step lesser.
Upvotes: 6
Reputation: 148178
Use removeClass
and do not pass any class to removeClass
and it will remove all classes that element has.
$(".color-green").click(function () {
$("#nav").removeClass().addClass("green");
});
Upvotes: 2
Reputation: 3654
$(".color-green").click(function () {
$("#nav").removeClass("color-orange");
$("#nav").removeClass("next-color");
$("#nav").removeClass("another-color");
$("#nav").removeClass("yet-another-color-but-green");
$("#nav").addClass("green");
});
Upvotes: 1
Reputation: 193301
Try this:
$("#nav").removeClass().addClass("green");
Without arguments removeClass will remove all the classes.
Also don't reselect $("#nav")
again and again, use method chaining, this increases performance.
Upvotes: 7