Last Updated: February 25, 2016
·
11.22K
· 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);

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside