leafiy
5/18/2018 - 6:53 PM

addClass removeClass hasClass #js

none

window.onload = init;

function init() {
  document.getElementById("myDiv").onclick = addMyClass;
}

function addMyClass() {
  var classString = this.className; // returns the string of all the classes for myDiv
  var newClass = classString.concat(" exmaple"); // Adds the class "main__section" to the string (notice the leading space)
  this.className = newClass; // sets className to the new string
}

function removeMyClass(){
    var classString = this.className; // returns the string of all the classes for myDiv
    var newClass = classString.replace(/\bexmaple\b/, ""); // Adds the class "main__section" to the string (notice the leading space)
    this.className = newClass; // sets className to the new string  
}





//another solution


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