How to sort an HTML table using JavaScript?

HTMLWeb DevelopmentFront End TechnologyJavascript

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

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>Sort a HTML Table Alphabetically</title>
<style>
   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;
   }
</style>
</head>
<body>
<h1>Sorting table example</h1>
<button onclick="sortTable()">Sort</button>
<table class="filterTable">
<tr>
<th>Name</th>
<th>BirthDay Month</th>
</tr>
<tr>
<td>Ron</td>
<td>January</td>
</tr>
<tr>
<td>Shawn</td>
<td>April</td>
<tr>
<tr>
<td>Caleb</td>
<td>December</td>
</tr>
<tr>
<td>Bruno</td>
<td>February</td>
</tr>
<tr>
<td>Jack</td>
<td>October</td>
</tr>
<tr>
<td>Max</td>
<td>November</td>
</tr>
</table>
<script>
   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;
               break;
            }
         }
         if (sortFlag) {
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            sorted = true;
         }
      }
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the Sort button −

raja
Published on 06-May-2020 18:02:15
Advertisements