Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DOMTokenList.toggle() — toggling a token

DOMTokenList.toggle() toggles a token's presence or forces it with force. It returns whether the token is present after the call.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

tokenList.toggle(token)
tokenList.toggle(token, force)

DOMTokenList.toggle() operates on a token list such as element.classList. Without force, it adds an absent token or removes a present one. Pass one token, not several space-separated classes.

force set to true ensures presence; false ensures absence. Repeating the same forced operation does not reverse the state. The result is true if the token is present afterward, or false if absent; it does not indicate whether anything changed.

An empty token throws a DOMException named SyntaxError; ASCII whitespace in the token causes InvalidCharacterError. This is a DOM API, not an ECMAScript built-in. The example requires a browser DOM.

Examples

const element = document.createElement('div');
const tokens = element.classList;
const results = [
  tokens.toggle('active'),
  tokens.toggle('active'),
  tokens.toggle('active', true),
  tokens.toggle('active', true),
  tokens.toggle('active', false)
];
console.log(JSON.stringify(results));
console.log(JSON.stringify(element.className));

Result

[true,false,true,true,false]
""

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources