Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sorcamarian/ff8db48c4dbf4f5000982072611955a2 to your computer and use it in GitHub Desktop.
Save sorcamarian/ff8db48c4dbf4f5000982072611955a2 to your computer and use it in GitHub Desktop.
Vanilla DOM Javascript - remove and add class - IE, old browsers
// Add class
DOMElement.className += " one";
// Example:
// var el = document.body;
// el.className += " two"
// Remove class
function removeDOMClass(element, className) {
var oldClasses = element.className,
oldClassesArray = oldClasses.split(" "),
newClassesArray = [],
newClasses;
// Sort
var currentClassChecked,
i;
for ( i = 0; i < oldClassesArray.length; i++ ) {
// Specified class will not be added in the new array
currentClassChecked = oldClassesArray[i];
if( currentClassChecked !== className ) {
newClassesArray.push(currentClassChecked);
}
}
// Order
newClasses = newClassesArray.join(" ");
// Apply
element.className = newClasses;
return element;
}
// Example:
// var el = document.body;
// removeDOMClass(el, "two")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment