DOM DOMTokenList.toggle() Method
The toggle() method of a DOMTokenList, usually element.classList.toggle(), adds a class if it's missing and removes it if it's present.
Description
The toggle() method switches a token: it removes it if present and adds it if not, returning whether it's present afterwards. With the optional force argument, it becomes a conditional add or remove, as in el.classList.toggle('active', isActive), which keeps the class in sync with a value.
Like add(), it throws a SyntaxError for an empty string and an InvalidCharacterError for tokens containing spaces, so pass one class name per call.
A common pattern is to toggle a class on the page's root or body element, such as dark or menu-open, and let CSS rules based on that class style the whole page, rather than changing many elements' styles in JavaScript.
Syntax
tokenList.toggle(token)
tokenList.toggle(token, force)Parameters
- tokenThe token (class name) to toggle.
- forceOptional.
trueto always add,falseto always remove.
Return Value
true if the token is now present, otherwise false.
Example
Browser Support
The following information will show you the current browser support for the DOMTokenList.toggle() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





