Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch classes jQuery

Tags:

jquery

I have a load of elements all named .client-dark and .client-light.

I want to switch these classes around and I'm trying it with...

 $('.clients-logo .container-fluid .row:nth-child(2)').find('.client-light').addClass('client-dark').removeClass('client-light');
 $('.clients-logo .container-fluid .row:nth-child(2)').find('.client-dark').addClass('client-light').removeClass('client-dark');

The first line of the above works but then the 2nd line overwrites it, is it possible to do both of these simultaneously?

like image 834
Liam Avatar asked Dec 02 '25 07:12

Liam


1 Answers

You can change both at once with toggleClass(). It supports using multiple class names separated by a space:

$('.clients-logo .container-fluid .row:nth-child(2)').find('.client-light,.client-dark').toggleClass('client-dark client-light');

Just search for both together and toggle both.

And a quick test to show it working: https://jsfiddle.net/TrueBlueAussie/r59uw7m6/ (just click anywhere in the output pane to toggle).

Note: as @gegillam also mentions, it is usually a good idea to have a base styling and a single class that changes it to the opposite when toggled.

like image 188
Gone Coding Avatar answered Dec 04 '25 19:12

Gone Coding