jQuery CSS Class Manipulation — Complete Guide to addClass, removeClass, toggleClass
In this tutorial, you will learn about jquery css class manipulation. We cover key concepts, practical examples, and best practices to help you master this topic.
jQuery CSS class manipulation methods let you add, remove, toggle, and check CSS classes on elements, enabling dynamic styling and state management without inline style manipulation.
What You'll Learn
- Using addClass, removeClass, toggleClass, hasClass
- Adding multiple classes at once
- Using functions to determine classes dynamically
- Class-based state management patterns
- Performance best practices
Why It Matters
CSS classes are the standard way to manage visual state on the web. jQuery's class methods abstract away the cumbersome element.classList API and provide consistent cross-browser behavior with powerful features like function callbacks.
Real-World Use
A tabbed interface where clicking a tab adds 'active' to the clicked tab, removes it from siblings, and shows the corresponding panel — all managed through CSS class toggling.
Class Manipulation Flow
flowchart LR
A[$('.element')] --> B[.addClass('active')]
A --> C[.removeClass('hidden')]
A --> D[.toggleClass('highlight')]
A --> E[.hasClass('selected')]
B --> F[DOM updated]
C --> F
D --> F
E --> G[Boolean result]
style A fill:#e6f3ff,stroke:#4a90d9,stroke-width:2px
addClass
// Add a single class
$('.box').addClass('highlight');
// Add multiple classes (space-separated)
$('.box').addClass('highlight animated border-rounded');
// Add multiple classes as array
$('.box').addClass(['highlight', 'animated', 'border-rounded']);
// Add classes based on a function
$('li').addClass(function(index, currentClass) {
return index % 2 === 0 ? 'even' : 'odd';
});
Expected output: Each element gets the specified classes. The function version adds 'even' to even-indexed items and 'odd' to odd-indexed items.
removeClass
// Remove a single class
$('.box').removeClass('highlight');
// Remove multiple classes
$('.box').removeClass('highlight animated');
// Remove all classes
$('.box').removeClass();
// Remove classes based on a function
$('li').removeClass(function(index, currentClass) {
var classes = currentClass.split(' ');
return classes.filter(function(c) {
return c.startsWith('temp-');
}).join(' ');
});
Expected output: Without arguments, removeClass() strips all classes from the element. The function version removes only classes matching a condition.
toggleClass
// Toggle a single class
$('.box').toggleClass('active');
// Toggle multiple classes
$('.box').toggleClass('highlight animated');
// Toggle with a boolean switch
var isEnabled = true;
$('.box').toggleClass('disabled', !isEnabled);
// Toggle based on a function
$('li').toggleClass(function(index, currentClass, switchArg) {
return index < 3 ? 'first-three' : 'rest';
});
Expected output: The class is added if absent, removed if present. With the boolean switch, the class is added when the switch is true, removed when false.
hasClass
// Check if element has a class
if ($('.box').hasClass('active')) {
console.log('Box is active');
}
// Checking multiple elements (returns true if ANY matches)
var hasError = $('input').hasClass('error');
if (hasError) {
console.log('At least one input has an error');
}
// In a click handler
$('.item').click(function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
$(this).addClass('selected');
}
});
Expected output: hasClass returns true if any element in the jQuery collection has the specified class.
Tabs Example with Class Manipulation
$('.tab').click(function() {
var tabId = $(this).data('tab');
// Update tab classes
$('.tab').removeClass('active');
$(this).addClass('active');
// Update panel classes
$('.panel').removeClass('active');
$('#' + tabId).addClass('active');
});
<div class="tabs">
<div class="tab active" data-tab="tab1">Tab 1</div>
<div class="tab" data-tab="tab2">Tab 2</div>
<div class="tab" data-tab="tab3">Tab 3</div>
</div>
<div class="panels">
<div id="tab1" class="panel active">Content 1</div>
<div id="tab2" class="panel">Content 2</div>
<div id="tab3" class="panel">Content 3</div>
</div>
Expected output: Clicking a tab removes 'active' from all tabs/panels and adds it to the clicked tab and its corresponding panel.
Accordion with Class Toggle
$('.accordion-header').click(function() {
var $body = $(this).next('.accordion-body');
// Close all other bodies
$('.accordion-body').not($body).slideUp().removeClass('open');
$('.accordion-header').not(this).removeClass('active');
// Toggle this body
$(this).toggleClass('active');
$body.slideToggle().toggleClass('open');
});
Form Validation with Classes
$('input').on('blur', function() {
var $input = $(this);
var value = $input.val().trim();
if (value === '') {
$input
.removeClass('valid')
.addClass('error');
$input.next('.error-message').text('This field is required');
} else {
$input
.removeClass('error')
.addClass('valid');
$input.next('.error-message').text('');
}
});
Expected output: On blur, inputs get an 'error' class with red border or a 'valid' class with green border. Error messages appear below invalid fields.
State Machine with Classes
var states = ['idle', 'loading', 'success', 'error'];
function setState(element, newState) {
var $el = $(element);
// Remove all state classes
states.forEach(function(s) {
$el.removeClass('state-' + s);
});
// Add the new state class
$el.addClass('state-' + newState);
}
// Usage
setState('.status-badge', 'loading');
// Later
setState('.status-badge', 'success');
Common Mistakes
Using .css() instead of class methods - Inline styles from .css() are hard to override and maintain. Use classes for state and .css() only for truly dynamic values.
Not removing classes before adding alternatives - Adding 'active' without removing it from siblings causes multiple elements to appear active. Always clear the group first.
Spelling errors in class names -
.addClass('backgound')silently fails (adds a misspelled class). No error is thrown. Use linters to catch typos.Forgetting the dot in .hasClass() -
.hasClass('active')does NOT need a dot prefix..hasClass('.active')always returns false.Using addClass where toggleClass is clearer - For toggle behavior, toggleClass expresses intent better than if/else with addClass/removeClass.
Practice Questions
- How do you add two classes to an element in one call?
- What does removeClass() do when called without arguments?
- How does toggleClass() behave differently from addClass/removeClass?
- What does hasClass() return when called on a set of multiple elements?
- How do you conditionally add a class using a function?
Challenge: Build a star rating widget where hovering over stars adds a 'hover' class, clicking sets a 'selected' class, and the rating value updates in real-time. Use only class manipulation for styling.
FAQ
Mini Project
Build a theme switcher with three themes (light, dark, high-contrast). Clicking a theme button removes all theme classes from the body and adds the selected one. Style common elements (background, text, links, buttons) using CSS classes for each theme.
What's Next
Classes control appearance. Learn how jQuery DOM manipulation methods modify the structure and content of elements beyond just styling.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro