Skip to content

Instantly share code, notes, and snippets.

@Aniket-508
Created January 14, 2022 04:59
Show Gist options
  • Save Aniket-508/9a94eb8d0d1c3b76dc19af413f875c9e to your computer and use it in GitHub Desktop.
Save Aniket-508/9a94eb8d0d1c3b76dc19af413f875c9e to your computer and use it in GitHub Desktop.
Javascript function to sort the list in ascending order.
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("[id of the ul tag or the list you want to sort]");
switching = true;
/* Make a loop that will continue until no switching has been done: */
while (switching) {
// Start by saying: no switching is done:
switching = false;
b = list.getElementsByTagName("LI");
// Loop through all list items:
for (i = 0; i < (b.length - 1); i++) {
// Start by saying there should be no switching:
shouldSwitch = false;
/* Check if the next item should switch place with the current item: */
if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
/* If next item is alphabetically lower than current item, mark as a switch and break the loop: */
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch and mark the switch as done: */
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment