HTML DOMTokenList toggle() methode

Definitie en gebruik

De toggle() methode verwijdert het opgegeven teken uit de lijst en retourneert false. Als het teken niet bestaat, wordt het toegevoegd en retourneert true.

Voorbeeld

Voorbeeld 1

Schakel de aan/uit van "myStyle":

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

Try it yourself

Voorbeeld 2

Voeg "myStyle" klasse toe aan het element:

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

Try it yourself

Voorbeeld 3

Verwijder "myStyle" klasse van het 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 between 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
Support Support Support Support Support

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