jQuery how to toggle back and forth?


I wanted to ask you guys how i can toggle back and forth when a button is clicked.

I have two “font-awesome” icon, and each time this icon is clicked i want it to change to the one who is not selected of the two. This is what i tried so far.

(".toggleOnOff").click(function(){ //noShow just has "display:none" Its used to hide/show an element on my page. (".helpFC").toggleClass(“noShow”),
//This one is used to remove the class on the to then add the other icon class name.


How can i then revert it? Is it by using “if” statements?

Appreciate any help i can get, thanks.


Plain js:

const element = document.getElementsByClassName("toggleOnOff")[elementIndex]
element. classList.toggle("yourClassName")

$( ".toggleOnOff" ).toggleClass( "yourClassName" )

Happy coding


But this only works with 1 class right?

Because i’d like to switch

<i class="fa-toggle-on"></i>

to ->

<i class="fa-toggle-off"></i>

And when pressing the button again i would like it to go to on again, and so forth. Thanks in advance. :slight_smile:

A simple google with better key words used to search with, it works out, thanks a lot for your quick answer.

You can do that with two statement:

$(element).toggleClass( "fa-toggle-on" );
$(element).toggleClass( "fa-toggle-off" );

or even in one statement:

$(element).toggleClass("fa-toggle-on fa-toggle-off");

or if necessary to identify your element with the current class:

$(".fa-toggle-on, .fa-toggle-off").toggleClass("fa-toggle-on fa-toggle-off");