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?
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>