0
0
HtmlHow-ToBeginner · 4 min read

How to Sort Table in HTML: Simple Guide with Example

To sort a table in HTML, use JavaScript to reorder the rows based on the clicked column. Add event listeners to table headers and rearrange rows dynamically with sort() on the data.
📐

Syntax

Sorting an HTML table requires JavaScript code that:

  • Selects the table and its rows.
  • Detects which column header was clicked.
  • Sorts the rows based on that column's cell values.
  • Rearranges the rows inside the table body.

This is done by using document.querySelector, addEventListener, and array sort() methods.

javascript
const table = document.querySelector('table');
const headers = table.querySelectorAll('th');

headers.forEach((header, index) => {
  header.addEventListener('click', () => {
    const rows = Array.from(table.tBodies[0].rows);
    rows.sort((rowA, rowB) => {
      const cellA = rowA.cells[index].textContent.trim();
      const cellB = rowB.cells[index].textContent.trim();
      return cellA.localeCompare(cellB, undefined, {numeric: true, sensitivity: 'base'});
    });
    rows.forEach(row => table.tBodies[0].appendChild(row));
  });
});
💻

Example

This example shows a simple HTML table with three columns. Clicking a column header sorts the table rows by that column's text.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sortable Table Example</title>
<style>
  table { border-collapse: collapse; width: 50%; margin: 20px auto; }
  th, td { border: 1px solid #ccc; padding: 8px; text-align: left; cursor: pointer; }
  th:hover { background-color: #f0f0f0; }
</style>
</head>
<body>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>City</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>Alice</td><td>30</td><td>New York</td></tr>
    <tr><td>Bob</td><td>25</td><td>Los Angeles</td></tr>
    <tr><td>Charlie</td><td>35</td><td>Chicago</td></tr>
    <tr><td>Diana</td><td>28</td><td>Miami</td></tr>
  </tbody>
</table>
<script>
const table = document.querySelector('table');
const headers = table.querySelectorAll('th');

headers.forEach((header, index) => {
  header.addEventListener('click', () => {
    const rows = Array.from(table.tBodies[0].rows);
    rows.sort((rowA, rowB) => {
      const cellA = rowA.cells[index].textContent.trim();
      const cellB = rowB.cells[index].textContent.trim();
      return cellA.localeCompare(cellB, undefined, {numeric: true, sensitivity: 'base'});
    });
    rows.forEach(row => table.tBodies[0].appendChild(row));
  });
});
</script>
</body>
</html>
Output
A table with columns Name, Age, City and four rows. Clicking any column header sorts the rows by that column's values alphabetically or numerically.
⚠️

Common Pitfalls

Common mistakes when sorting tables include:

  • Not converting numbers to numbers before sorting, causing wrong order.
  • Sorting only once without toggling ascending/descending order.
  • Sorting the entire table including headers instead of just the body rows.
  • Not trimming cell text, which can cause unexpected sorting results.

Always ensure you sort only the <tbody> rows and handle data types properly.

javascript
/* Wrong: Sorting entire table including header row */
const rows = Array.from(table.rows); // includes header

/* Right: Sorting only tbody rows */
const rows = Array.from(table.tBodies[0].rows);
📊

Quick Reference

Tips for sorting HTML tables:

  • Use table.tBodies[0].rows to get only data rows.
  • Use localeCompare with {numeric: true} for mixed text and numbers.
  • Add click listeners on th elements for user interaction.
  • Re-append sorted rows to the tbody to update the table.
  • Consider toggling sort order for better UX.

Key Takeaways

Use JavaScript to sort only the table body rows, not headers.
Attach click events to table headers to trigger sorting.
Use localeCompare with numeric option for correct sorting of numbers and text.
Always re-append sorted rows to update the table display.
Trim cell text to avoid sorting errors caused by extra spaces.