How to add/remove a class in JavaScript?

Pacerier picture Pacerier · Jul 22, 2011 · Viewed 81.8k times · Source

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?

Answer

emil picture emil · Feb 5, 2015

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,' ');
  }
}