Skip to content

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().

if (condition) {
element.classList.add("active");
} else {
element.classList.remove("active");
}
if (isVisible) {
button.classList.remove("hidden");
} else {
button.classList.add("hidden");
}

This rule is not configurable.

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().

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.