JSFiddle - React, Tailwind, and code Playground
by amkrtchyan
HTML
<!DOCTYPE html>
<html>
<head>
<title>Sort a HTML Table Alphabetically</title>
<style>
table {
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
}
th {
cursor: pointer;
}
th, td {
text-align: left;
padding: 16px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
</style>
</head>
<body>
<p><strong>Click the headers to sort the table.</strong></p>
<p>The first time you click, the sorting direction is ascending (A to Z).</p>
<p>Click again, and the sorting direction will be descending (Z to A):</p>
<table id="myTable">
<tr>
<!--When a header is clicked, run the sortTable function, with a parameter, 0 for sorting by names, 1 for sorting by country:-->
<th onclick="sortTable(0)">Name</th>
<th onclick="sortTable(1)">Country</th>
<th onclick="sortTable(2)">id</th>
</tr>
<tr style="display: none">
<td>Berglunds snabbkop</td>
<td>Sweden</td>
<td>1</>
</tr>
<tr>
<td>North/South</td>
<td>UK</td>
<td>2</>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
<td>3</>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
<td>4</>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Italy</td>
<td>12</>
</tr>
<tr>
<td>Paris specialites</td>
<td>France</td>
<td>21</>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
<td>51</>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Canada</td>
<td>71</>
</tr>
</table>
<script>
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");
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;
rows = table.rows;
/*Loop through all table rows (except the
first, which contains table...