HTML Table Sort Accessibility
Make HTML tables sortable with accessible buttons and aria-sort for screen readers.
Code
<table id="table">
<thead>
<tr>
<th><button onclick="sort(0)">Name <span aria-hidden="true">↕</span></button></th>
<th><button onclick="sort(1)">Age <span aria-hidden="true">↕</span></button></th>
</tr>
</thead>
<tbody>
<tr><td>Alice</td><td>30</td></tr>
<tr><td>Bob</td><td>25</td></tr>
</tbody>
</table>
<script>
let dir = 1;
function sort(col) {
dir *= -1;
const rows = [...table.querySelectorAll('tbody tr')];
rows.sort((a, b) => dir * (a.cells[col].textContent > b.cells[col].textContent ? 1 : -1));
rows.forEach(r => table.querySelector('tbody').appendChild(r));
}
</script>Report a problem with this exampleOpens a pre-filled issue on GitHub.