Last active
May 6, 2022 03:40
-
-
Save EmmanuelBeziat/ecbee4d69d9d41fa53c8dddf1d3e6262 to your computer and use it in GitHub Desktop.
Add "switch" method to element.classList property
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
Object.defineProperty(DOMTokenList.prototype, 'switch', { | |
writable: false, | |
enumerable: false, | |
configurable: false, | |
value (...list) { | |
const el = this | |
const matchedClass = list.filter(cls => el.contains(cls)) | |
if (!matchedClass.length) { | |
el.add(list[0]) | |
return | |
} | |
el.add(list[list.indexOf(matchedClass[0]) + 1] || list[0]) | |
el.remove(matchedClass) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use:
If the element already has a class that's in that list, it will start from this specific class.
Working Example
// Todo : throw errors if class isn't provided