Last active
September 13, 2018 15:54
-
-
Save sorcamarian/ff8db48c4dbf4f5000982072611955a2 to your computer and use it in GitHub Desktop.
Vanilla DOM Javascript - remove and add class - IE, old browsers
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
// 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