Skip to content

Instantly share code, notes, and snippets.

@hemant-tivlabs
Last active March 31, 2021 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hemant-tivlabs/0a878d6018108a0055ac9db7742ee23a to your computer and use it in GitHub Desktop.
Save hemant-tivlabs/0a878d6018108a0055ac9db7742ee23a to your computer and use it in GitHub Desktop.
Use modClass instead of jQuery's `addClass` or `removeClass` to save on writing conditional if-else statements

jQuery.modClass()

In my opinion, instead of using the traditional if-else statements to switch CSS classes, using a conditional operator in conjunction with modClass makes the code simpler, easier to read and saves on code lines.

Instead of doing the traditional way:

if (i < 5) {
  jQuery('ul').removeClass('many-items');
} else {
  jQuery('ul').addClass('many-items');
}

We simply use:

jQuery('ul').modClass(i < 5 ? 'remove' : 'add', 'many-items');

Hope this is useful. Thanks!

jQuery.fn.extend({
modClass: function(mod, classNames) {
if(mod == 'add') {
return this.each(function () {
this.classList.add(...classNames.split(' '));
});
}
if(mod == 'remove') {
return this.each(function () {
this.classList.remove(...classNames.split(' '));
});
}
}
});
// Call examples:
// jQuery('body').modClass('add', 'xxx yyy zzz');
// jQuery('h1').modClass('remove', 'text-center');
// jQuery('p').modClass(use_italic ? 'add' : 'remove', 'text-italicise');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment