The toggle()
method of the DOMTokenList
interface removes an existing token from the list and returns false
. If the token doesn't exist it's added and the function returns true
.
The toggle()
method of the DOMTokenList
interface removes an existing token from the list and returns false
. If the token doesn't exist it's added and the function returns true
.
js
toggle(token) toggle(token, force)
A boolean value, true
or false
, indicating whether token
is in the list after the call or not.
In the following example we retrieve the list of classes set on a <span>
element as a DOMTokenList
using Element.classList
. We then replace a token in the list, and write the list into the <span>
's Node.textContent
.
First, the HTML:
html
<span class="a b">classList is 'a b'</span>
Now the JavaScript:
js
const span = document.querySelector("span"); const classes = span.classList; span.addEventListener("click", () => { const result = classes.toggle("c"); span.textContent = `'c' ${ result ? "added" : "removed" }; classList is now "${classes}".`; });
The output looks like this and it will change each time you click on the text:
The second parameter can be used to determine whether the class is included or not. This example would include the 'c' class only if the browser window is over 1000 pixels wide:
js
span.classList.toggle("c", window.innerWidth > 1000);
Specification |
---|
DOM Standard # ref-for-dom-domtokenlist-toggle① |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
toggle |
8 | 12 | 3.6 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
force_parameter |
24 | 12 | 24 | No | 15 | 7 | 4.4 | 25 | 24 | 14 | 7 | 1.5 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle