Portions of this content are ©1998–2022 by individual mozilla.org contributors. Earn 10 reputation in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity. This has already been discussed, along with browser support.
Adding/removing (toggling) the class with ‘toggleClass’
Wasted resources as we’re including stuff we don’t need too. We used thefor…ofloop to iterate over the collection of elements and added a click event handler to each element. Select a group of elements using the document.querySelectorAll() method. Similarly, if you need to remove one or more classes, you can use the remove()method. You can pass as many classes to the add() method as necessary.
A function returning one or more space-separated class names or an array of class names to be added to the existing class name. Receives the index position of the element in the set and the existing class name as arguments. Within the function, this refers to the current element in the set. We added a click event listener to the document object, so any time an element is clicked, a function is invoked. Use the target property on the event object to get the clicked element. A function returning one or more space-separated class names to be added to the existing class name.
- To remove the old-fashioned way, split the classname on whitespace, remove the one you don’t want from the resulting array, then join the array again…
- We added a click event listener to the document object, so any time an element is clicked, a function is invoked.
- You can pass as many classes to the add() method as necessary.
- In other words, event.target gives us access to the DOM element the user clicked.
- In this article, we will learn how to add the class name property to the element, along with understanding the implementation through the example.
Using classList is a convenient alternative to accessing an element’s list of classes as a space-delimited string via element.className. The Element.classList is a read-only property that returns a live DOMTokenList collection of the classattributes of the element.
It’s the total opposite of what should be happening. JQuery makes you as a developer reliant on a framework, and (I’m going to say it!)… lazy, to some extent. I’d succumbed to being lazy, and at times have included the mighty jquery.js file for a few simple lines of code. On each iteration, add a click event listener to the element that adds a specific class. The target property is a reference to the object on which the event was dispatched. A DOMTokenList representing the contents of the element’s class attribute. If the class attribute is not set or empty, it returns an empty DOMTokenList, i.e. a DOMTokenList with the length property equal to 0.