Created
June 23, 2019 23:35
-
-
Save ajmeese7/5c07b8a41288843daf5d477c47bb73a8 to your computer and use it in GitHub Desktop.
Toggle class in vanilla JS
This file contains hidden or 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
// This is a general function that removes one class and adds another | |
function toggleClass(target, addedClass) { | |
// If target is an element rather than a list, it is converted to array form | |
if (!NodeList.prototype.isPrototypeOf(target)) { | |
target = [target]; | |
} | |
// Allows for multiple elements to be toggled, such as by using the querySelectorAll() method | |
[].forEach.call(target, (element) => { | |
if (element.classList.contains(addedClass)) { | |
element.classList.remove(addedClass); | |
} else { | |
element.classList.add(addedClass); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment