Table of Contents

<HTMLElement>.toggleClass()

Toggles a class for an HTMLElement, i.e. it removes the class, if it exists, and adds it, if it doesn’t.

Usage:
HTMLElement = Element.toggleClass(className)
Member of:
Element, any valid HTMLElement.
Parameters:
className – the name of the class to toggle as String object, or as quoted string (required).
Returns:
The same HTMLElement that it was called on, thus allowing for command chaining.
Notes:
  • This function is a simple wrapper for the classList.toggle() function. The only difference is that this function returns the HTMLElement and thus allows chaining other functions for neater and/or more compact code.

Examples

Simple example:

let foo = document.getElementById('foo');
foo.toggleClass('bar');

Chaining allows for very compact code:

document.getElementById('foo').toggleClass('bar').attr('data-value', '123');

… and also allows for very neat and readable code:

document.getElementById('foo')
	.toggleClass('bar')
	.attr('data-value', '123')
;

See also

More information