Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add and remove classes in Javascript without jQuery

I'm looking for a fast and secure way to add and remove classes from an html element without jQuery.
It also should be working in early IE (IE8 and up).

like image 628
Peter Eberle Avatar asked Nov 04 '14 13:11

Peter Eberle


People also ask

How do I remove a class from a div?

Use the classList. remove() method to remove a class from a div element, e.g. box. classList. remove('my-class') .

Has class add and remove jQuery?

The jQuery toggleClass() add or remove one or more classes from the selected elements in such a way that if the selected element already has the class, then it is removed; if an element does not have the class, then it is added i.e. toggle classes.

How do you clear a class in Javascript?

To remove all classes from an element, set the element's className property to an empty string, e.g. box. className = '' . Setting the element's className property to an empty string empties the element's class list.


1 Answers

Another approach to add the class to element using pure JavaScript

For adding class:

document.getElementById("div1").classList.add("classToBeAdded"); 

For removing class:

document.getElementById("div1").classList.remove("classToBeRemoved"); 

Note: but not supported in IE <= 9 or Safari <=5.0

like image 114
Shoaib Chikate Avatar answered Oct 12 '22 22:10

Shoaib Chikate