Skip to content

Instantly share code, notes, and snippets.

@Fedik
Last active December 29, 2015 16:18
Show Gist options
  • Save Fedik/7e243a4615f3a600b74b to your computer and use it in GitHub Desktop.
Save Fedik/7e243a4615f3a600b74b to your computer and use it in GitHub Desktop.
JavaScript raw has/add/remove Class
Element.prototype.hasClassName = function(className) {
return this.classList ? this.classList.contains(className) : !!this.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}
Element.prototype.addClass = function(className) {
if (this.classList){this.classList.add(className);}
else if (!this.hasClass(className)){this.className += " " + className;}
return this;
}
Element.prototype.removeClass = function(className) {
if (this.classList){this.classList.remove(className);}
else if (this.hasClass(className)) {
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
this.className = this.className.replace(reg, ' ');
}
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment