How To Add, Remove, Toggle Class Of A DOM Element In JavaScript
Maybe your like
With the classList property of a DOM element, we can add, remove, check, and toggle an element’s class in JavaScript.
Print the classes of a DOM element
The classList property of a DOM element returns a DOMTokenList, which contains all the classes of the element.
Take a look at the code below:
OutputJavaScriptHTMLRunConsoleClearAdd class to an element
We can use the add method to add classes to the element. This is shown below:
OutputJavaScriptHTMLRunConsoleClearThe classList contains live data, meaning it will automatically update the class when a class is added or removed:
OutputJavaScriptHTMLRunConsoleClearRemove the class of an element
We can use the remove method to remove classes from an element. Take a look at the following code:
OutputJavaScriptHTMLRunConsoleClearCheck if a DOM element contains a certain class
To check if there is a class present in a DOM element, we can use the contains method, as shown below:
OutputJavaScriptHTMLRunConsoleClearToggle a class
To toggle a class, we can use the toggle method. The toggle method will:
- Add the class if the class is not present in the element.
- Remove the class if the class is present in the element.
The toggle method returns true if the class is added, and false if the class is removed.
OutputJavaScriptHTMLRunConsoleClearReplace a class
To replace an existing class, we can use the replace method. The replace method returns true if the class was successfully replaced; otherwise, it returns false.
OutputJavaScriptHTMLRunConsoleClearRelevant Answers
Explore Courses
Free Resources
License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)Tag » Add Class To Dom Element Js
-
How To Add A Class Name - W3Schools
-
Javascript - How To Add A Class To A Given Element? - Stack Overflow
-
How To Add A Class To DOM Element In JavaScript? - GeeksforGeeks
-
assList - Référence Web API | MDN
-
How To Add A Class To An Element Using JavaScript - Javatpoint
-
Add Class To Clicked Element Using JavaScript - Bobbyhadz
-
4 Easy Ways To Add Class To An Element Using JavaScript - Webinuse
-
How To Add A Class To A DOM Element - Flavio Copes
-
.addClass() | JQuery API Documentation
-
Add Class To Html Element Javascript Code Example - Code Grepper
-
Add Classes To An Element - JavaScript Tutorial
-
How To Add A Class To A Given Element In JavaScript
-
AddClass: Adds CSS Class To DOM Element - Gists · GitHub
-
Add A CSS Class To An HTML Element With JavaScript/jQuery