Easiest way to toggle 2 classes in jQuery

JqueryToggleclass

Jquery Problem Overview


If I have class .A and class .B and want to switch in between on button click, what's a nice solution for that in jQuery? I still don't understand how toggleClass() works.

Is there an inline solution to put it in onclick="" event?

Jquery Solutions


Solution 1 - Jquery

If your element exposes class A from the start, you can write:

$(element).toggleClass("A B");

This will remove class A and add class B. If you do that again, it will remove class B and reinstate class A.

If you want to match the elements that expose either class, you can use a multiple class selector and write:

$(".A, .B").toggleClass("A B");

Solution 2 - Jquery

Here is a simplified version: (albeit not elegant, but easy-to-follow)

$("#yourButton").toggle(function() 
{
        $('#target').removeClass("a").addClass("b"); //Adds 'a', removes 'b'
        
}, function() {
        $('#target').removeClass("b").addClass("a"); //Adds 'b', removes 'a'
        
});

Alternatively, a similar solution:

$('#yourbutton').click(function()
{
     $('#target').toggleClass('a b'); //Adds 'a', removes 'b' and vice versa
});

Solution 3 - Jquery

I've made a jQuery plugin for working DRY:

$.fn.toggle2classes = function(class1, class2){
  if( !class1 || !class2 )
    return this;

  return this.each(function(){
    var $elm = $(this);

    if( $elm.hasClass(class1) || $elm.hasClass(class2) )
      $elm.toggleClass(class1 +' '+ class2);

    else
      $elm.addClass(class1);
  });
};

// usage example:
$(document.body).on('click', () => {
  $(document.body).toggle2classes('a', 'b')
})

body{ height: 100vh }
.a{ background: salmon }
.b{ background: lightgreen }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Click anywhere

Solution 4 - Jquery

Your onClick request:

<span class="A" onclick="var state = this.className.indexOf('A') > -1; $(this).toggleClass('A', !state).toggleClass('B', state);">Click Me</span>

Try it: https://jsfiddle.net/v15q6b5y/


Just the JS à la jQuery:

$('.selector').toggleClass('A', !state).toggleClass('B', state);

Solution 5 - Jquery

The easiest solution is to toggleClass() both classes individually.

Let's say you have an icon:

    <i id="target" class="fa fa-angle-down"></i>

To toggle between fa-angle-down and fa-angle-up do the following:

    $('.sometrigger').click(function(){
        $('#target').toggleClass('fa-angle-down');
        $('#target').toggleClass('fa-angle-up');
    });

Since we had fa-angle-down at the beginning without fa-angle-up each time you toggle both, one leaves for the other to appear.

Solution 6 - Jquery

Here's another 'non-conventional' way.

  • It implies the use of underscore or lodash.
  • It assumes a context where you:
  • the element doesn't have an init class (that means you cannot do toggleClass('a b'))
  • you have to get the class dynamically from somewhere

An example of this scenario could be buttons that has the class to be switched on another element (say tabs in a container).

// 1: define the array of switching classes:
var types = ['web','email'];

// 2: get the active class:
var type = $(mybutton).prop('class');

// 3: switch the class with the other on (say..) the container. You can guess the other by using _.without() on the array:
$mycontainer.removeClass(_.without(types, type)[0]).addClass(type);

Solution 7 - Jquery

Toggle between two classes 'A' and 'B' with Jquery.

> $('#selecor_id').toggleClass("A B");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStewie GriffinView Question on Stackoverflow
Solution 1 - JqueryFrédéric HamidiView Answer on Stackoverflow
Solution 2 - JqueryRion WilliamsView Answer on Stackoverflow
Solution 3 - JqueryvsyncView Answer on Stackoverflow
Solution 4 - JquerygdibbleView Answer on Stackoverflow
Solution 5 - JqueryOvercomerView Answer on Stackoverflow
Solution 6 - JqueryLuca ReghellinView Answer on Stackoverflow
Solution 7 - JqueryLove KumarView Answer on Stackoverflow