Skip to content

Instantly share code, notes, and snippets.

@agryson
Last active December 15, 2016 12:11
Show Gist options
  • Save agryson/4244292 to your computer and use it in GitHub Desktop.
Save agryson/4244292 to your computer and use it in GitHub Desktop.
This function will append or remove a class from an element cleanly by ensuring whitespace is how it should be.
/**
* Attribution: Alexander Gryson (agryson.net)
* Appends or removes a class to/from an element
* @param {boolean} bool True if appending class, false if removing
* @param {string} targetID ID of target element
* @param {string} classString Class to be added / removed (case sensitive)
*/
function classChange(bool, targetID, classString){
var target = document.getElementById(targetID);
var targetPresent;
var newClass;
if (target.className.indexOf(classString) > 0){
newClass = ' ' + classString;
targetPresent = true;
} else if(target.className.indexOf(classString) === -1 && target.className.length > 0){
newClass = ' ' + classString;
targetPresent = false;
}else if(target.className.indexOf(classString) === -1){
newClass = classString;
targetPresent = false;
}else{
newClass = classString;
targetPresent = true;
}
if(targetPresent && !bool){
target.className = target.className.replace(newClass, '');
} else if (!targetPresent && bool){
target.className += newClass;
}
}
@agryson
Copy link
Author

agryson commented Dec 11, 2012

Alternatively, as I've recently discovered, all of this is also natively supported by pure JavaScript

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