SyntaxStudy
Sign Up
jQuery Beginner 4 min read

jQuery CSS Classes

Managing CSS classes is one of the most common tasks in front-end development. jQuery provides four focused methods — addClass(), removeClass(), toggleClass(), and hasClass() — that make class manipulation concise and readable.

Adding and Removing Classes

addClass() appends one or more space-separated class names to each matched element without disturbing existing classes. removeClass() removes the specified classes, or removes all classes when called with no arguments.

Toggling Classes

toggleClass() adds the class if the element does not have it, and removes it if it does. An optional boolean second argument forces the class on (true) or off (false), which is handy when you want to synchronise state with a variable.

  • addClass('active highlight') — add two classes at once
  • removeClass('disabled') — remove one class
  • toggleClass('open') — flip a class on/off
  • hasClass('error') — returns true or false

Because these methods operate on jQuery collections, a single call updates every matched element simultaneously — no loop required.

Example
// Add a class
$('button').addClass('btn-primary');

// Remove a class
$('input').removeClass('error');

// Toggle a class on click
$('#menu-toggle').on('click', function () {
    $('nav').toggleClass('open');
});

// Conditional toggle using a boolean
var isLoggedIn = true;
$('#user-panel').toggleClass('hidden', !isLoggedIn);

// Check if an element has a class
if ($('#alert').hasClass('danger')) {
    console.log('Danger alert is visible');
}
Pro Tip

Use toggleClass() with a boolean expression to keep your UI state in sync with data.