Properties of HTML elements being used
- classList: This property returns the class name(s) of the element as a DOMTokenList object. This object has some well-known methods including contains(), add(), remove(), and toggle().
- contains(): This method returns a boolean value indicating if a particular class name is present or not.
- add(): This method is used to add one or more class names to an element.
- remove(): This method is used to remove one or more class names from an element.
- toggle(): This method belongs to the DOMTokenList object, and is used to toggle between the classes
These are the following methods for toggling an element Class:
Table of Content
- By Using the toggle() method:
- By Using contains(), add() and remove() method:
How to Toggle an Element Class in JavaScript ?
Toggling the class means if there is no class name assigned to the element, then a class name can be assigned to it dynamically or if a certain class is already present, then it can be removed dynamically by just using the toggle() or by using contains(), add(), remove() methods of DOMTokenList object within JavaScript.