classListToggles
Prefer using classList.toggle() over conditional classList.add() and classList.remove().
✅ This rule is included in the browser stylistic preset.
The classList.toggle() method provides a concise and expressive way to conditionally add or remove a CSS class.
Using conditional logic with classList.add() and classList.remove() creates unnecessary code duplication and makes the intent less clear.
This rule suggests replacing any if/else used to toggle a class name from a list with the equivalent toggle().
Examples
Section titled “Examples”if (condition) { element.classList.add("active");} else { element.classList.remove("active");}
if (isVisible) { button.classList.remove("hidden");} else { button.classList.add("hidden");}element.classList.toggle("active", condition);
button.classList.toggle("hidden", !isVisible);Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you need to support very old browsers that do not implement the two-parameter version of classList.toggle() (Internet Explorer 11 and earlier), you might need to use the conditional add()/remove() pattern.
For modern browsers and applications, prefer toggle().
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
unicorn/prefer-classlist-toggle
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.