HTML Table Sorter

Organize your data. This script adds click events to your table headers, allowing users to sort the table contents alphabetically without needing a database query.

Name Country
John DoeUSA
Anna SmithUK
Peter JonesCanada
Maria GarciaSpain

Click on the headers (Name or Country) to sort.

Copy the Script

<script>
function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("myTable");
  switching = true;
  dir = "asc"; 
  while (switching) {
    switching = false;
    rows = table.rows;
    for (i = 1; i < (rows.length - 1); i++) {
      shouldSwitch = false;
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          shouldSwitch = true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          shouldSwitch = true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      switchcount ++;      
    } else {
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}
</script>

Frequently Asked Questions

Yes. The script generally tries to compare values as strings, which works for numbers in most simple cases. For advanced data (dates, currencies), you might need a more robust library like DataTables.

No. The sorting happens entirely in the browser (Client Side) by rearranging the DOM elements instantly.

This simple script sorts by one column at a time. Clicking a header sorts that specific column in ascending order.