Created
February 3, 2022 10:18
-
-
Save mklasen/d80d6a56e7cc8c8c041bbd12214866ae to your computer and use it in GitHub Desktop.
Re-order options in a select element alphabatically by it's text value
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
main.querySelectorAll("select").forEach(select => { | |
let options = select.querySelectorAll("option"); | |
Array.from(options) | |
.sort((a, b) => { | |
if (a.text.toUpperCase() > b.text.toUpperCase()) return 1; | |
else if (a.text.toUpperCase() < b.text.toUpperCase()) return -1; | |
else return 0; | |
}) | |
.forEach(el => { | |
select.appendChild(el); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment