I am using JavaScript and I want to add/remove a Class attribute if a button is clicked. I am able to add the class, but I don\'t know how to remove it. how can I do that?
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!this.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,' ');
}
}
You can use RegExp in theses three functions to check class existance, add class, and remove class. Here is the source openjs