Styling with classList0%

Styling with classList

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Styling with classList in Modern JavaScript

Manipulating CSS classes via JavaScript is the industry-standard method for altering visual states (e.g., dropdown toggles, modal dialogs, validation borders, theme switches). The classList API provides a clean, safe, and intuitive interface for managing an element's class attributes without string manipulation errors.


1. Why classList Replaced className

Historically, developers manipulated element.className as a raw string:

JavaScript
// LEGACY (Error-Prone):
element.className += ' active'; // Could result in 'buttonactive' if space is omitted!
element.className = element.className.replace('active', '').trim();

Modern browsers provide element.classList, which returns a DOMTokenList offering dedicated utility methods.


2. Core classList Methods

add(), remove(), and replace()

JavaScript
const alertBox = document.querySelector('.alert');
 
// Adding classes (supports multiple arguments)
alertBox.classList.add('alert-warning', 'shadow-lg');
 
// Removing classes
alertBox.classList.remove('alert-info');
 
// Replacing one class with another
alertBox.classList.replace('alert-warning', 'alert-danger');

contains()

Checks whether an element currently has a specific class. Returns a boolean:

JavaScript
const themeToggleBtn = document.querySelector('#btn-theme');
 
if (document.body.classList.contains('dark-mode')) {
console.log('Current theme is Dark');
} else {
console.log('Current theme is Light');
}

3. toggle() with Optional Boolean Force

The toggle() method adds the class if it is missing, and removes it if it is present:

JavaScript
const drawer = document.querySelector('#sidebar-drawer');
 
// Simple toggle
drawer.classList.toggle('open');

The Force Parameter

classList.toggle(className, force) accepts a second boolean argument:

  • force === true: Class is always added.
  • force === false: Class is always removed.
JavaScript
function handleScroll() {
const isScrolledPastHeader = window.scrollY > 150;
const navbar = document.querySelector('.main-nav');
 
// If scrolled past 150px, force add 'sticky'; otherwise force remove it
navbar.classList.toggle('sticky', isScrolledPastHeader);
}
 
window.addEventListener('scroll', handleScroll);

4. Comparing classList vs. Inline Styles (style attribute)

FeatureclassList.add('my-class')element.style.color = 'red'
Separation of ConcernsHigh (Styles stay in CSS files)Low (Styles hardcoded in JS)
CSS SpecificityNormal class specificityInlines have higher specificity (hard to override)
Media Queries / Pseudo-classesSupported via CSS rules (:hover, @media)Not supported directly in inline styles
MaintainabilityCentralized in CSS stylesheetsScattered across JS code files
Rule of Thumb: Use classList for all visual states. Only use element.style for truly dynamic, runtime-calculated values like mouse coordinates (style.transform = ...) or canvas dimensions.

5. Practical Example: Accordion Component

JavaScript
function initAccordion() {
const accordionHeaders = document.querySelectorAll('.accordion-header');
 
accordionHeaders.forEach(header => {
header.addEventListener('click', () => {
const accordionItem = header.closest('.accordion-item');
const isOpen = accordionItem.classList.contains('active');
 
// Close all sibling items
document.querySelectorAll('.accordion-item').forEach(item => {
item.classList.remove('active');
});
 
// If it was not open, open it
if (!isOpen) {
accordionItem.classList.add('active');
}
});
});
}

Interactive Quiz

Practice Quiz

Question 1
What type of object is element.classList?
Question 2
What does element.classList.toggle('highlight', true) do?
Question 3
Which classList method replaces one CSS class with another in a single call?
Question 4
Why is using classList preferred over assigning element.style properties for visual states?
Question 5
What does element.classList.contains('active') return if the element has classes 'nav-link active show'?
Next Lesson

Event Listeners

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext