MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Styling with classList0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
3.1querySelectorAll & forEach3.2Traversing DOM Nodes3.3Dynamic Element Creation & Removal3.4Styling with classList
HomeTutorialsJavaScript for IntermediateStyling with classList
Event Listeners

Styling with classList

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

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:

1// LEGACY (Error-Prone):
2element.className += ' active'; // Could result in 'buttonactive' if space is omitted!
3element.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()

1const alertBox = document.querySelector('.alert');
2 
3// Adding classes (supports multiple arguments)
4alertBox.classList.add('alert-warning', 'shadow-lg');
5 
6// Removing classes
7alertBox.classList.remove('alert-info');
8 
9// Replacing one class with another
10alertBox.classList.replace('alert-warning', 'alert-danger');

contains()

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

1const themeToggleBtn = document.querySelector('#btn-theme');
2 
3if (document.body.classList.contains('dark-mode')) {
4 console.log('Current theme is Dark');
5} else {
6 console.log('Current theme is Light');
7}

3. toggle() with Optional Boolean Force

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

1const drawer = document.querySelector('#sidebar-drawer');
2 
3// Simple toggle
4drawer.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.
1function handleScroll() {
2 const isScrolledPastHeader = window.scrollY > 150;
3 const navbar = document.querySelector('.main-nav');
4 
5 // If scrolled past 150px, force add 'sticky'; otherwise force remove it
6 navbar.classList.toggle('sticky', isScrolledPastHeader);
7}
8 
9window.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

1function initAccordion() {
2 const accordionHeaders = document.querySelectorAll('.accordion-header');
3 
4 accordionHeaders.forEach(header => {
5 header.addEventListener('click', () => {
6 const accordionItem = header.closest('.accordion-item');
7 const isOpen = accordionItem.classList.contains('active');
8 
9 // Close all sibling items
10 document.querySelectorAll('.accordion-item').forEach(item => {
11 item.classList.remove('active');
12 });
13 
14 // If it was not open, open it
15 if (!isOpen) {
16 accordionItem.classList.add('active');
17 }
18 });
19 });
20}

Interactive Quiz• Knowledge Check

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

Previous LessonNext Lesson
Dynamic Element Creation & RemovalEvent Listeners

Practice Quiz

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

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext