Skip to content

Instantly share code, notes, and snippets.

@hcl1687
Created January 13, 2017 02:01
Show Gist options
  • Save hcl1687/333f2e0696b05f270cdfe5d5339e7012 to your computer and use it in GitHub Desktop.
Save hcl1687/333f2e0696b05f270cdfe5d5339e7012 to your computer and use it in GitHub Desktop.
operate class attribute
Element.prototype.hasClassName = function (a) {
return new RegExp("(?:^|\\s+)" + a + "(?:\\s+|$)").test(this.className);
};
Element.prototype.addClassName = function (a) {
if (!this.hasClassName(a)) {
this.className = [this.className, a].join(" ");
}
};
Element.prototype.removeClassName = function (b) {
if (this.hasClassName(b)) {
var a = this.className;
this.className = a.replace(new RegExp("(?:^|\\s+)" + b + "(?:\\s+|$)", "g"), " ");
}
};
Element.prototype.toggleClassName = function (a) {
this[this.hasClassName(a) ? "removeClassName" : "addClassName"](a);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment