Skip to content

Instantly share code, notes, and snippets.

@mklasen
Created February 3, 2022 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mklasen/d80d6a56e7cc8c8c041bbd12214866ae to your computer and use it in GitHub Desktop.
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
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