user1038814
user1038814

Reputation: 9657

change name of class name when clicked in jquery

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

Answers (5)

insomiac
insomiac

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

efesar
efesar

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

Explosion Pills
Explosion Pills

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

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

$(this).addClass('...');

or

$(this).attr('class','...');

Upvotes: 1

We Are All Monica
We Are All Monica

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

Related Questions