How to sort an HTML table using JavaScript?

To sort an HTML table using JavaScript, the code is as follows −


 Live Demo

<!DOCTYPE html>
<title>Sort a HTML Table Alphabetically</title>
   button {
      padding: 10px;
      margin-bottom: 5px;
      font-size: 16px;
      font-weight: bold;
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   table {
      border-spacing: 0;
      width: 100%;
      border: 1px solid #ddd;
   th, td {
      border-top: 1px solid black;
      text-align: left;
      padding: 16px;
<h1>Sorting table example</h1>
<button onclick="sortTable()">Sort</button>
<table class="filterTable">
<th>BirthDay Month</th>
   function sortTable() {
      var filterTable, rows, sorted, i, x, y, sortFlag;
      filterTable = document.querySelector(".filterTable");
      sorted = true;
      while (sorted) {
         sorted = false;
         rows = filterTable.rows;
         for (i = 1; i < rows.length - 1; i++) {
            sortFlag = false;
            x = rows[i].getElementsByTagName("TD")[0];
            y = rows[i + 1].getElementsByTagName("TD")[0];
            if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
               sortFlag = true;
         if (sortFlag) {
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            sorted = true;


The above code will produce the following output −

On clicking the Sort button −