Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
}
@rosell-dk

This comment has been minimized.

Copy link

@rosell-dk rosell-dk commented Oct 17, 2016

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:

// @author Bjørn Rosell (derived from Peter Boughton) 
function removeClass​(el, className​) {
   el​.className=el​.className​.replace​(new RegExp​("​(\\s|^​)"+className+"​(?!\\S​)","g"​),""​)​.trim​(​)
}

BTW:
I have done an extensive test of candidates for removing a class. You can find it here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment