add/remove
Apply or remove named states.
classList lets JavaScript change state while CSS keeps control over the visual design.
panel.classList.add("is-open");
panel.classList.toggle("is-active", isActive);
panel.style.setProperty("--progress", "75%");
DOM & HTML Interaction
The classList API can add, remove, toggle and check classes without rewriting the full class attribute.
Most visual changes should happen through CSS classes. JavaScript decides the state; CSS decides what that state looks like.
Inline styles are useful for dynamic values such as coordinates, progress or CSS variables, but they should not replace a design system.
Apply or remove named states.
Switch a class on and off.
Check whether a class is present.
Set truly dynamic inline values.
Examples
button.classList.toggle("is-active", selected);
button.setAttribute("aria-pressed", String(selected));
button.style.background = "yellow"; button.style.color = "black"; button.style.borderRadius = "999px";
Code patterns
These patterns are the DOM moves you use constantly: select, read, change, create, navigate and render.
Let CSS handle the design.
panel.classList.add("is-open");
The second argument makes state explicit.
panel.classList.toggle("is-active", currentStep === 2);
contains reads the current class state.
const isOpen = panel.classList.contains("is-open");
Inline values can feed CSS custom properties.
meter.style.setProperty("--progress", `${percent}%`);
Rules that matter
DOM APIs are powerful because they affect the live page. Use them with stable hooks, clear state and safe text updates.
is-open and is-active communicate behavior.
toggle(name, condition) avoids accidental flipping.
JavaScript should not become a stylesheet.
Visual active state should match ARIA state where needed.
Coordinates and progress values are good examples.
classList is safer when multiple classes exist.
Production thinking
classList keeps behavior and visual design connected without mixing their responsibilities.
When class changes reveal, hide or select content, update focus and ARIA state as well.
Production teams can redesign CSS classes without rewriting JavaScript behavior.
Class-driven interactions should not hide important crawlable content by default.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
If you can explain the DOM operation and its failure path, you are ready to use it in real UI code.
Senior audit upgrade
Prefer textContent, createElement, templates and replaceChildren for normal UI rendering. Reach for innerHTML only when the markup is controlled and the risk is understood.
const item = document.createElement("li");
item.textContent = userInput;
list.replaceChildren(item);