Last active
April 12, 2016 20:27
-
-
Save bradorego/7b509290f53ae45b626961e4c9509293 to your computer and use it in GitHub Desktop.
Add, Remove, Toggle classname for an element in Vanilla Javascript
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
Element.prototype.hasClass = function (name) { | |
var classes = this.className.split(" "), | |
hasClass = false; | |
for (var i = 0; i < classes.length; i++) { | |
if (classes[i] === name) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
Element.prototype.removeClass = function (name) { | |
if (this.hasClass(name)) { | |
this.className = this.className.replace(name, ''); | |
return true; | |
} else { | |
return false; | |
} | |
}; | |
Element.prototype.addClass = function (name) { | |
if (!this.hasClass(name)) { | |
this.className += ' ' + name; | |
return true; | |
} else { | |
return false; | |
} | |
}; | |
Element.prototype.toggleClass = function (name) { | |
if (this.hasClass(name)) { | |
this.removeClass(name); | |
} else { | |
this.addClass(name); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment