Last active
February 1, 2020 17:14
-
-
Save Maksims/5356227 to your computer and use it in GitHub Desktop.
HTMLElement extension to add, remove, toggle, detect Classes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
I can confirm that the RegEx for removeClass works. Only minor thing is that it doesn't remove all instances of a class name, if the class name should appear in the class list several times (it might happen if a function simply adds the classname without testing if its already there). Simply adding a "g" flag to the RegEx is not enough to deal with that.
There exists an alternative RegEx, which does not have that minor problem, and which is just as small:
BTW:
I have done an extensive test of candidates for removing a class. You can find it here