Last Updated: February 25, 2016
·
10.79K
· dhaffner

Conditionally toggle a class on a element with 1 jQuery statement

Until now if I had a an element, for example an a tag, and I wanted to add or remove a class based on some condition I would do it like this:

if (condition)
    $('a.some-link').addClass('some-class');
else
    $('a.some-link').removeClass('some-class');

I've known about toggleClass for a while but I never read its documentation. You can pass a boolean as the second parameter to toggleClass that will determine whether the given class is added or removed, like so:

$('a.some-link').toggleClass('some-class', condition);