Skip to content

Instantly share code, notes, and snippets.

@mardix
Forked from Maksims/DOMClass.js
Created December 8, 2018 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mardix/757de74c79ab25e926da78cbdb89534d to your computer and use it in GitHub Desktop.
Save mardix/757de74c79ab25e926da78cbdb89534d to your computer and use it in GitHub Desktop.
HTMLElement extension to add, remove, toggle, detect Classes.
HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;
HTMLElement.prototype.addClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) {
this.className = this.className.trim() + ' ' + string[i];
}
}
}
HTMLElement.prototype.removeClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim();
}
}
HTMLElement.prototype.toggleClass = function(string) {
if (string) {
if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim();
} else {
this.className = this.className.trim() + ' ' + string;
}
}
}
HTMLElement.prototype.hasClass = function(string) {
return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment