# unicorn/prefer-classlist-toggle

> Require `classList.toggle()` instead of choosing between `add()` and `remove()`

`classList.toggle(name, force)` adds the class if `force` is true and removes it if `force` is false. That's one call instead of an `if` and an `else` that repeat the element and the class name.

`--fix` rewrites the code to `toggle()`.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"unicorn/prefer-classlist-toggle" = "error" # or "warn"
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 3} */}
```js
if (isOpen) {
  menu.classList.add("open");
} else {
  menu.classList.remove("open");
}

isOpen ? menu.classList.add("open") : menu.classList.remove("open");

menu.classList[isOpen ? "add" : "remove"]("open");
```

Not reported:

{/* good */}
```js
menu.classList.toggle("open", isOpen);
```

`toggle(name, undefined)` flips the class instead of removing it. If the condition can be `undefined`, pass `Boolean(isOpen)`.

The two calls must use the same element and the same class:

{/* good */}
```js
if (isOpen) {
  menu.classList.add("open");
} else {
  menu.classList.remove("closing");
}
```
