Reputation: 9657
I have a div with class name: .sel-display-on. When clicked, I want to change it to .sel-display-off with jquery. Is this possible at all? Will the css properties of this new class name be applied?
$('.sel-display-on').click(function (e) {
e.stopPropagation();
// change class name to .sel-display-off
});
Upvotes: 2
Views: 171
Reputation: 5664
You can do something like this :
$('.sel-display-on').click(function (e) {
e.stopPropagation();
// change class name to .sel-display-off
$(this).removeClass('sel-display-on').addClass('sel-display-off');
});
You can also do this using toggleClass :
$('.sel-display-on').click(function (e) {
e.stopPropagation();
// change class name to .sel-display-off
$(this).toggleClass(function(){
if($(this).is('.sel-display-on'){
return "sel-display-off";
} else {
return "sel-display-on";
}
});
Upvotes: 0
Reputation: 1392
http://api.jquery.com/addClass/
http://api.jquery.com/removeClass/
Yes, use the two functions above to achieve this. Also, the new class will be applied immediately.
One other note: after you remove the class .sel-display-on, then you will no longer be able to select that element using .sel-display-on.
Upvotes: 0
Reputation: 191749
The answer to all of your questions is "yes"
You can use addClass
, removeClass
, toggleClass
, and attr('class', ...)
as needed.
The e.stopPropagation
above is not necessary if this is on a div
, unless you are stopping some other functionality you have bound to it.
Upvotes: 0
Reputation: 114367
$(this).addClass('...');
or
$(this).attr('class','...');
Upvotes: 1
Reputation: 13334
$(this).removeClass('sel-display-on').addClass('sel-display-off');
Or, if you are sure that this element won't have any other class names (not very good practice, but may be faster):
$(this).attr('class', 'sel-display-off');
Upvotes: 4