<table> <tr> <th>Firstname</th> <th>Lastname</th> <th>Born</th> </tr> <tr> <td>Jean</td> <td>Lamarck</td> <td>1744</td> </tr> <tr> <td>Charles</td> <td>Darwin</td> <td>1809</td> </tr> </table>
const $table = document.querySelector('table') const $$tr = [...document.querySelectorAll('tr:not(:first-child)')] document.querySelectorAll('th').forEach($th => { $th.onclick = e => { const i = e.target.cellIndex $$tr.sort((a, b) => { a = a.querySelector(`:nth-child(${i + 1})`).textContent b = b.querySelector(`:nth-child(${i + 1})`).textContent return Intl.Collator().compare(a, b) }).forEach($tr => $table.appendChild($tr)) } })
th:hover { cursor: pointer; color: orange; }