Skip to content

Instantly share code, notes, and snippets.

@EmmanuelBeziat
Last active May 6, 2022 03:40
Show Gist options
  • Save EmmanuelBeziat/ecbee4d69d9d41fa53c8dddf1d3e6262 to your computer and use it in GitHub Desktop.
Save EmmanuelBeziat/ecbee4d69d9d41fa53c8dddf1d3e6262 to your computer and use it in GitHub Desktop.
Add "switch" method to element.classList property
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)
}
})
@EmmanuelBeziat
Copy link
Author

EmmanuelBeziat commented May 6, 2022

How to use:

// Trigger on a specific event
document.querySelector('.element').classList.switch('class1', 'class2', 'class3', 'class4')

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment