Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / JavaScript Tutorial / Chapter 4: DOM Manipulation & Events
JAVASCRIPT ⏱ 10 min read

DOM Traversal, Styles & CSS Classes

Rather than hardcoding styles in JavaScript, modern apps toggle pre-defined CSS classes to create smooth UI state transitions.

What is it?

The `classList` API allows JavaScript to add, remove, toggle, and check CSS classes on elements (`classList.add`, `classList.remove`, `classList.toggle`, `classList.contains`).

Why is it used?

Keeps styling inside CSS stylesheets and logic inside JavaScript, maintaining clean separation of concerns.

Detailed Explanation

ClassList Operations: • `el.classList.add('active')`: Adds class if not present. • `el.classList.remove('hidden')`: Removes class. • `el.classList.toggle('dark-theme')`: Adds class if absent, removes if present! • `el.classList.contains('active')`: Returns boolean check. DOM Traversal: • `el.parentElement`: Returns parent node. • `el.children`: Returns collection of child elements. • `el.closest('.card')`: Finds closest matching ancestor (great for event delegation).

Syntax Structure

Syntax Blueprint
element.classList.toggle('active');
const card = button.closest('.course-card');

Code Example

JAVASCRIPT Code
// Toggle Dark Mode Theme via classList
const themeToggleBtn = document.getElementById("themeToggleBtn");

themeToggleBtn.addEventListener("click", () => {
  const isDark = document.documentElement.getAttribute("data-theme") === "dark";
  
  if (isDark) {
    document.documentElement.setAttribute("data-theme", "light");
    localStorage.setItem("igm_theme", "light");
  } else {
    document.documentElement.setAttribute("data-theme", "dark");
    localStorage.setItem("igm_theme", "dark");
  }
});

Explanation of the Code

• Reads current theme attribute. • Flips attribute and saves preference into `localStorage` so it persists on page reloads.

Expected Output

The page instantly shifts colors between warm light parchment and dark charcoal theme.

Real-World Application

This is the exact theme toggling logic used across the IGM Computers learning platform.

Common Mistakes to Avoid

• Setting styles manually via `el.style.backgroundColor = '...'` for every state change instead of toggling CSS classes. • Forgetting that `element.children` returns only HTML element nodes (ignoring text/comment nodes).

Quick Practice Challenge

Toggle an 'expanded' class on a sidebar menu element whenever a hamburger button is clicked.

Key Takeaways

• Use `classList.toggle()` for accordion drawers, dark mode, and modal visibility. • Use `element.closest('.selector')` to traverse up to the nearest matching parent. • Keep visual rules in CSS; let JavaScript only toggle state classes.