-
-
Save mardix/757de74c79ab25e926da78cbdb89534d to your computer and use it in GitHub Desktop.
HTMLElement extension to add, remove, toggle, detect Classes.
This file contains hidden or 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