JavaScript Interview Question #57

How do classList methods work?

DOM, Events & Event Loop Fundamentals Mid-Level Intermediate

Quick Interview Answer

The classList property provides a convenient API for manipulating an element's CSS classes. Common methods include add, remove, toggle, contains, and replace.

Detailed Explanation

The classList property provides a convenient API for manipulating an element's CSS classes. Common methods include add, remove, toggle, contains, and replace.

classList avoids manually parsing and rebuilding the complete class attribute and is particularly useful for interactive UI states such as active, hidden, selected, or disabled styling.

Code Example

const panel = document.querySelector(".panel");

panel.classList.add("active");
panel.classList.remove("hidden");
panel.classList.toggle("expanded");

if (panel.classList.contains("active")) {
    console.log("Panel is active");
}