Remove/Replace Classes
There are a few ways to remove all classes, and leave only one. You could use $.attr
:
$(".box").on("click", function(){
$(this).attr("class", "test");
});
This sets the full value of class
to a single classname. Alternatively, you could set the className
on the element itself:
$(".box").on("click", function(){
this.className = "test";
});
Or, you could call $.removeClass()
without any arguments (which removes all classes), and then follow that up by adding your test
class:
$(".box").on("click", function(){
$(this).removeClass().addClass("test");
});
Avoid Ambiguity
I'm assuming that you don't have any other .box
elements on the page - if you do, the selector used here would need to be modified just a bit to affect only the boxes we wish to target.
If these boxes were within a larger container:
<div id="boxes">
<div class="box w-25 h-25">...</div>
<div class="box w-30 h-30">...</div>
</div>
We might change our selector to include the container id
:
$("#boxes .box").on("click" function(){
/* React */
});
Toggle On/Off
From the comments, the OP expressed a desire to remember the original classes, and swap .test
out for them if the element were clicked on a second time. Below is one possible solution to this:
$(".box").on("click", function(){
// Store original class attribute as data
$(this).data("o") || $(this).data("o", $(this).attr("class"));
// Set new class attribute to test, or to original
$(this).attr("class", function(i,o){
return o != $(this).data("o") ? $(this).data("o") : "test" ;
});
});