Skip to content

Instantly share code, notes, and snippets.

@danprince
Created May 18, 2014 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danprince/05cb72052484355f3adc to your computer and use it in GitHub Desktop.
Save danprince/05cb72052484355f3adc to your computer and use it in GitHub Desktop.
Quick jQuery style add/remove class implementation.
(function() {
// Helper which turns class string into array
function getClassList(element) {
return element.getAttribute('class').split(' ');
}
// Add class with this name to the element
function addClass(name) {
var classes = getClassList(this);
if(classes.indexOf(name) < 0) {
classes.push(name);
}
this.setAttribute('class', classes.join(' '));
}
// Remove class with this name
function removeClass(name) {
var classes, index;
classes = getClassList(this);
if((index = classes.indexOf(name)) >= 0) {
classes.splice(index, 1);
}
this.setAttribute('class', classes.join(' '));
}
Element.prototype.addClass = addClass;
Element.prototype.removeClass = removeClass;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment