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>How the snippet works
2 ARIA attributes are set explicitly, covering states native semantics alone do not expose.
Script and styles anchor onto ids table, so behavior and styling stay decoupled from the tag names.
Watch out for
- ARIA attributes only help when they match real behavior — an announced state the script never updates is worse than none.
Statements that matter
<table id="table">
<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>
Interactive Tools for This Topic
WCAG Color Contrast CheckerCalculate WCAG 2.1 color contrast ratios between foreground and background colors. Verify AA and AAA compliance levels for normal and large text accessibility.Tailwind Color Palette GeneratorGenerate a balanced 50-950 Tailwind CSS custom property color scale from any hex, RGB, or HSL base color with WCAG 2.1 contrast ratios for every stop.HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
FAQ
- Which non-generic elements does the markup use?
- `<table>`, `<thead>`, `<tr>`, `<th>`, `<button>`, `<tbody>`, `<td>` — each carries native semantics (or a browser behavior) that generic containers do not.
Report a problem with this exampleOpens a pre-filled issue on GitHub.