Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add/remove a class in JavaScript?

Since element.classList is not supported in IE 9 and Safari-5, what's an alternative cross-browser solution?

No-frameworks please.

Solution must work in at least IE 9, Safari 5, FireFox 4, Opera 11.5, and Chrome.

Related posts (but does not contain solution):

  1. how to add and remove css class

  2. Add and remove a class with animation

  3. Add remove class?

like image 731
Pacerier Avatar asked Jul 22 '11 08:07

Pacerier


People also ask

How you can add remove a class to an element?

You can use the classList. add OR classList. remove method to add/remove a class from a element.


2 Answers

Here is solution for addClass, removeClass, hasClass in pure javascript solution.

Actually it's from http://jaketrent.com/post/addremove-classes-raw-javascript/

function hasClass(ele,cls) {   return !!ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); }  function addClass(ele,cls) {   if (!hasClass(ele,cls)) ele.className += " "+cls; }  function removeClass(ele,cls) {   if (hasClass(ele,cls)) {     var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');     ele.className=ele.className.replace(reg,' ');   } } 
like image 74
emil Avatar answered Sep 23 '22 14:09

emil


Look at these oneliners:

  1. Remove class:

    element.classList.remove('hidden'); 
  2. Toggle class (adds the class if it's not already present and removes it if it is)

    element.classList.toggle('hidden'); 

That's all! I made a test - 10000 iterations. 0.8s.

like image 23
Sergio Belevskij Avatar answered Sep 22 '22 14:09

Sergio Belevskij