classList Toggles Classes With Force
Mutate class names through classList instead of className strings: toggle accepts a force argument for three-way intent and replace swaps atomically.
Code
// classList:类名的增删查改不碰 className 字符串
const panel = document.querySelector('#panel');
panel.classList.add('open', 'frozen');
console.log('contains open :', panel.classList.contains('open'));
// toggle 的 force 参数表达三态意图:true 加、false 移、缺省翻转
panel.classList.toggle('open', false);
console.log('contains open :', panel.classList.contains('open'));
panel.classList.toggle('muted'); // 无 force:有则移、无则加
console.log('contains muted:', panel.classList.contains('muted'));
// replace 原子替换:类名不存在时返回 false 且不改动
const swapped = panel.classList.replace('frozen', 'thawed');
console.log('replaced :', swapped, '->', panel.getAttribute('class'));What the code does
Demo state sits in top-level bindings: panel, swapped.
Points of care
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Applying it
The demo output is labeled (contains open :, contains muted:, replaced :), so every printed line maps back to its originating operation.
Statements that matter
const swapped = panel.classList.replace('frozen', 'thawed');
panel.classList.toggle('muted'); // 无 force:有则移、无则加
console.log('contains muted:', panel.classList.contains('muted'));
const panel = document.querySelector('#panel');
Interactive Tools for This Topic
FAQ
- Does classList Toggles Classes With Force run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.