Last active
February 5, 2025 01:06
-
-
Save jf990/176ad061e30844ea4bb7759e9a690f30 to your computer and use it in GitHub Desktop.
Update an elements class definition by removing and adding classes
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
/** | |
* Remove and add classes to any element. Removes are performed before adds. | |
* @param {string} Selector to target. Must resolve to a single element. | |
* @param {string|array} Classes to add. If using single string, can only be a single class. Otherwise use array of strings for each class to add. | |
* @param {string|array} Classes to remove. If using single string, can only be a single class. Otherwise use array of strings for each class to remove. | |
*/ | |
function setClassList(selector, classesToAdd, classesToRemove) { | |
let element = document.querySelector(selector); | |
if (Array.isArray(classesToRemove) && classesToRemove.length > 0) { | |
for (let i = 0; i < classesToRemove.length; i+= 1) { | |
if (classesToRemove[i]) { | |
element.classList.remove(classesToRemove[i]); | |
} | |
} | |
} else if (classesToRemove) { | |
element.classList.remove(classesToRemove); | |
} | |
if (Array.isArray(classesToAdd) && classesToAdd.length > 0) { | |
for (let i = 0; i < classesToAdd.length; i+= 1) { | |
if (classesToAdd[i]) { | |
element.classList.add(classesToAdd[i]); | |
} | |
} | |
} else if (classesToAdd) { | |
element.classList.add(classesToAdd); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment