Element.classList.toggle
Toggles a class name in the element's class list: removes it if present, adds it if not
Syntax
element.classList.toggle(token, force?)Parameters
| Parameter | Type | Description |
|---|---|---|
| token | string | The class name to toggle |
| force | boolean | If true, add the class; if false, remove it |
Return Value
true if the class is now present, false otherwise
Examples
const menu = document.querySelector('.menu')!
menu.classList.toggle('open')function setDarkMode(enabled: boolean) {
document.body.classList.toggle('dark-mode', enabled)
}const btn = document.querySelector('button')!
btn.addEventListener('click', () => {
btn.classList.toggle('pressed')
})Understanding Element.classList.toggle
The Element.classList.toggle method in JavaScript toggles a class name in the element's class list: removes it if present, adds it if not. It belongs to the DOMTokenList object and is one of the most widely used methods for working with domtokenlist values in modern JavaScript and TypeScript applications.
The method signature is element.classList.toggle(token, force?). It accepts 2 parameters: token, force. When called, it returns true if the class is now present, false otherwise. Understanding when and how to use toggle() helps you write more expressive, readable code.
Common use cases for Element.classList.toggle include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-classlist-add, dom-classlist-remove, dom-classlist-contains, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Element.classList.toggle is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
More DOMTokenList Methods
Other methods in the DOMTokenList object
Related Tools
More DOMTokenList Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.