Build a chainable classes() helper with add, remove, and toggle
A dashboard still ships a few legacy widgets that run in an embedded browser without classList. The team wants one small helper that changes classes on many elements at once and reads like jQuery: classes('.row').remove('loading').add('ready').
Implement classes(target). It returns a wrapper object for the matched elements.
const rows = classes(target);
rows.add(names) // adds the classes to every element; returns rows
rows.remove(names) // removes the classes from every element; returns rows
rows.toggle(names, force?) // toggles the classes on every element; returns rows
rows.has(name) // true if at least one element has the class
document.querySelectorAll when classes() is called. The selection is fixed at that moment: elements added to the page later are not affected.add, remove and toggle do nothing and return the wrapper, and has returns false.names is a string of one or more class names separated by any whitespace (spaces, tabs, newlines). Extra whitespace is ignored, so ' btn \t primary ' means btn and primary.class attribute, split the same way. A class that appears twice counts once.add keeps existing classes in their order and appends new ones at the end, in the order given. A class is never added twice.toggle(names) flips each class on each element independently: added where it is missing, removed where it is present. If force is true, it behaves like add; if force is false, like remove.has(name) checks a single class name.getAttribute('class') and setAttribute('class', ...). Do not use classList. This also makes the helper work on SVG elements, whose className is not a string.class="").class attribute and gains no class keeps having no attribute.// <li class="item">A</li>
// <li class="item active">B</li>
classes('li.item').add('seen');
// <li class="item seen">A</li>
// <li class="item active seen">B</li>
classes('li.item').toggle('active').has('active');
// first li gains "active", second li loses it => true
const button = document.querySelector('button'); // class="btn"
classes(button).add('btn primary large').remove('large');
// <button class="btn primary">
classes('.does-not-exist').add('x').has('x');
// => false