×

Save Your Code

If you click the save button, your code will be saved, and you get an URL you can share with others.

By clicking the "Save" button you agree to our terms and conditions.

Report Error

×

Save to Google Drive

If you have a Google account, you can save this code to your Google Drive.

Google will ask you to confirm Google Drive access.

×

Open from Google Drive

If you have saved a file to Google Drive, you can open it here:

Result Size: 625 x 571
x
 
<!DOCTYPE html>
<html>
<title>Sort a HTML List Alphabetically</title>
<body>
<p>Click the button to sort the list ascending (A to Z):</p>
<p>Click again to sort the list descending (Z to A):</p>
<button onclick="sortListDir()">Sort</button>
<ul id="id01">
  <li>Oslo</li>
  <li>Stockholm</li>
  <li>Helsinki</li>
  <li>Berlin</li>
  <li>Rome</li>
  <li>Madrid</li>
</ul>
<script>
function sortListDir() {
  var list, i, switching, b, shouldSwitch, dir, switchcount = 0;
  list = document.getElementById("id01");
  switching = true;
  // Set the sorting direction to ascending:
  dir = "asc"; 
  // 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,
      based on the sorting direction (asc or desc): */
      if (dir == "asc") {
        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;
        }
      } else if (dir == "desc") {
        if (b[i].innerHTML.toLowerCase() < b[i + 1].innerHTML.toLowerCase()) {
          /* if next item is alphabetically higher than current item,
          mark as a switch and break the loop: */
×

Report a Problem: