== .toggleClass ==

.toggleClass()

Toggles a class for an HTMLElement, i.e. it removes the class, if it exists, and adds it, if it doesn’t.
Usage:
[[mdn>Web/API/HTMLElement|HTMLElement]] = Element.''toggleClass''(className)
Member of:
Element, any valid [[mdn>Web/API/HTMLElement|HTMLElement]].
Parameters:
className – the name of the class to toggle as [[mdn>Web/JavaScript/Reference/Global_Objects/String|String]] object, or as quoted string (required).
Returns:
The same [[mdn>Web/API/HTMLElement|HTMLElement]] that it was called on, thus allowing for command chaining.
Notes:
* This function is a simple wrapper for the [[mdn>Web/API/Element/classList|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 ===== * [[toolbox:classes:addclass:index|.addClass()]] * [[toolbox:classes:removeclass:index|.removeClass()]] * [[toolbox:classes:hasclass:index|.hasClass()]] ===== More information ===== * [[mdn>Web/API/HTMLElement|HTMLElement]] on MDN. * [[mdn>Web/API/Element/classList|classList]] on MDN.