Favorites

DOM DOMTokenList.toggle() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
DOMTokenList.toggle()
DOM DOMTokenList MethodThis method is supported by all modern browsers.
Updated 28th November 2026

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. true to always add, false to always remove.

Return Value

true if the token is now present, otherwise false.

Example

<style>.dark{background:#111;color:#eee}</style>
<button id="theme" type="button">Toggle dark mode</button>
const btn = document.getElementById('theme');
btn.addEventListener('click', () => {
  const dark = document.body.classList.toggle('dark');
  console.log('dark mode:', dark);
});
btn.click();
document.body.classList.toggle('compact', window.innerWidth < 400);

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.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee