HTML DOMTokenList toggle() method

Definition and Usage

The toggle() method removes the given tag from the list and returns false. If the tag does not exist, it adds and returns true.

Instance

Example 1

Toggle the open/close state of "myStyle":

const list = element.classList;
list.toggle("mywStyle");

Try It Yourself

Example 2

Add the class "myStyle" to the element:

const list = element.classList;
list.add("myStyle");

Try It Yourself

Example 3

Remove the class "myStyle" from the element:

const list = element.classList;
list.remove("myStyle");

Try It Yourself

Example 4

Add multiple classes to an element:

element.classList.add("myStyle", "anotherClass", "thirdClass");

Try It Yourself

Example 5

Remove multiple classes from an element:

element.classList.remove("myStyle", "anotherClass", "thirdClass");

Try It Yourself

Example 6

Get the number of classes of an element:

let numb = element.classList.length;

Try It Yourself

Example 7

Toggle classes to create a dropdown button:

document.getElementById("myBtn").onclick = function() {myFunction()};
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

Try It Yourself

Syntax

domtokenlist.toggle(token)

Parameter

Parameter Description
token Required. The token to be toggled.

Return Value

None.

Browser Support

domtokenlist.toggle() is a DOM Level 4 (2015) feature.

It is supported by all browsers:

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Supported Supported Supported Supported Supported

Internet Explorer 11 (or earlier versions) does not support domtokenlist.toggle().

Related Pages

length Property

item() Method

add() Method

remove() Method

replace() Method

forEach() Method

entries() Method

keys() Method

values() Method

DOMTokenList Object