Skip to content

Instantly share code, notes, and snippets.

@ajmeese7
Created June 23, 2019 23:35
Show Gist options
  • Save ajmeese7/5c07b8a41288843daf5d477c47bb73a8 to your computer and use it in GitHub Desktop.
Save ajmeese7/5c07b8a41288843daf5d477c47bb73a8 to your computer and use it in GitHub Desktop.
Toggle class in vanilla JS
// 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