Ad

RemoveClass Using JavaScript

- 1 answer

I'm trying to add/remove a class using JavaScript. (Please don't post about JQuery, because that's irrelevant.) I came upon this answer, which suggested using regular expression to remove the class. Here's the code:

function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }
}

I'm going to be adding and removing the same class. The problem is, how ever many times I do that, that's how many spaces get added to the class name. For example, if I add and remove the class 5 times, there will be 5 spaces between the 2 class names.

How can I prevent the spaces from coming?

CodePen

Code Snippet

var myDiv = document.getElementById('myDiv'),
  par = document.getElementById('par');

myDiv.addEventListener('click', function() {
  if (hasClass(myDiv, 'tryThis')) {
    removeClass(myDiv, 'tryThis');
  } else {
    addClass(myDiv, 'tryThis');
  }
  console.log(myDiv.className);
});



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, ' ');
  }
}
#myDiv {
  width: 100px;
  height: 100px;
  background-color: green;
}
.tryThis {
  border: 2px solid orange;
}
<div id="myDiv" class="hello">Click Me</div>
<p id="par"></p>

Ad

Answer

There's two solutions. The first (and easiest) is to use classList. The only downfall to this solution is that you won't be able to keep support for browsers that are older than its implementation.

As for the second solution, which keeps support for old browsers and extends off your regex solution, I'd suggest passing a function to replace that checks if both sides of the class name are whitespace. If they are, return ' ' otherwise return ''.

function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
    ele.className = ele.className.replace(reg, function(match) {
      if (match.match(/^\s.+\s$/) !== null) {
        return ' ';
      } else {
        return '';
      }
    });
  }
}

Edit: There's also the option of using a shim, sham, shiv, polyfill, etc.

Ad
source: stackoverflow.com
Ad