The browser
classList and dataset
Switch an element's classes on and off, and keep your own data on it with data-*.
Why it exists
You could change the look straight from JavaScript (el.style.color = …), but then styling gets smeared across the code where no designer will find it. Classes split the duties: CSS knows how a sold-out product looks, and JavaScript only knows that it's sold out. Before classList, classes were edited as the className string — glued and cut by hand, easily breaking the neighbouring classes. classList treats classes as a set: add one without touching the rest.
Where it's used
- UI states:
activeon the selected tab,openon a menu,sold-outon a product,erroron a form field. - Dark mode: a
darkclass on<html>, and CSS repaints everything else. dataset: a product id on the Buy button, a category on a filter item, a price on a menu item.- Tests and handlers find elements by classes and
data-*:[data-id="7"].
Syntax
el.classList.add("sold-out")
el.classList.remove("active")
el.classList.toggle("open") // there — remove it, not there — add it
el.classList.toggle("active", isOn) // add it only if isOn
el.classList.contains("hit") // true / false
el.dataset.price // the data-price attribute, a stringExamples
function setSoldOut(li, soldOut) {
li.classList.toggle("sold-out", soldOut);
}
function priceOf(li) {
return Number(li.dataset.price);
}function toggle(classes, name, force = !classes.has(name)) {
if (force) classes.add(name);
else classes.delete(name);
return force;
}
const classes = new Set(["dish"]);
toggle(classes, "sold-out"); // → true
toggle(classes, "sold-out"); // → false
toggle(classes, "hit", false); // → false
[...classes].join(" "); // → "dish"classList.toggle on a Set: without a second argument it flips, with one it sets.function datasetKey(attribute) {
return attribute.slice(5).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
}
datasetKey("data-sold-out"); // → "soldOut"
datasetKey("data-price"); // → "price"dataset turns attribute names into properties.function selectTab(tabs, name) {
for (const tab of tabs) {
tab.classList.toggle("active", tab.dataset.tab === name);
}
}
// selectTab(document.querySelectorAll(".tab"), "menu")
// — exactly one tab is left with the active classtoggle with a condition for each one.Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
classList is a live view of the class attribute, a lot like a Set of strings. add and remove never create duplicates and don't complain if the class isn't there. toggle(name) flips the class and returns true if it's now present. With a second argument, toggle(name, condition) no longer flips — it sets: adds for a true condition, removes for a false one — handy when the state is computed.
className is the same attribute as one string. Assigning el.className = "dish" replaces every class at once.
data-* attributes are HTML's approved way to keep your own data in markup. The dataset object translates names: data-sold-out ↔ dataset.soldOut (a hyphen + letter → a capital letter). Values are always strings: both data-price="250" and data-ready="false". Any attribute can also be read and written with getAttribute / setAttribute.
Traps
How it differs from…
When to pick something else
For values that change smoothly and continuously (a position while dragging, the width of a progress bar) you'd run out of classes — change el.style or CSS variables instead. And don't keep big data or objects in dataset: only short string labels like ids. The data itself lives in JavaScript.
Practice
Lessons where this appears
- A website for the Purrfect CaféTale · Chapter 18 · DOM: the page as a tree
- The Purrfect Café menuWorkshop · Chapter 18 · DOM: the page as a tree
- Cats looking for a homeLab · Chapter 18 · DOM: the page as a tree
- The Crooked SelectorBoss · Chapter 18 · DOM: the page as a tree
- Building the to-do listWorkshop · Chapter 23 · Project: a to-do app
- Filtering to-dosLab · Chapter 23 · Project: a to-do app