HTML Table Sort Accessibility

Make HTML tables sortable with accessible buttons and aria-sort for screen readers.

HtmlData Integrity

Code

htmlsnippet
21 lines
<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

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.