Sortable HTML Tables - Order Rows with Header Click

Order HTML table rows alphabetical or numerial order, increasing or decreasing order. Click the table header to select a column to sort by. Click a header twice for reverse order.

JavaScript and CSS

Include the CSS and JavaScript in your project and add the class="sortable" to any table tag in the HTML.

No. Model Price Range 0-100
1 Model S $83,900 651 km 1.99 s
2 Model 3 $42,900 437 km 3.1 s
3 Model X $99,990 564 km 2.5 s
4 Model Y $54,990 531 km 3.7 s

Tap the headers to reorder.

Open the table in the interactive HTML-CSS-JS editor »

JavaScript

document.addEventListener('click', function (e) {
  try {
    function findElementRecursive(element, tag) {
      return element.nodeName === tag ? element : 
       findElementRecursive(element.parentNode, tag)
    }
    var descending_th_class = ' dir-d '
    var ascending_th_class = ' dir-u '
    var ascending_table_sort_class = 'asc'
    var regex_dir = / dir-(u|d) /
    var regex_table = /\bsortable\b/
    var alt_sort = e.shiftKey || e.altKey
    var element = findElementRecursive(e.target, 'TH')
    var tr = findElementRecursive(element, 'TR')
    var table = findElementRecursive(tr, 'TABLE')
    function reClassify(element, dir) {
      element.className = element.className.replace(regex_dir, '') + dir
    }
    function getValue(element) {
      return (
        (alt_sort && element.getAttribute('data-sort-alt')) || 
      element.getAttribute('data-sort') || element.innerText
      )
    }
    if (regex_table.test(table.className)) {
      var column_index
      var nodes = tr.cells
      for (var i = 0; i < nodes.length; i++) {
        if (nodes[i] === element) {
          column_index = element.getAttribute('data-sort-col') || i
        } else {
          reClassify(nodes[i], '')
        }
      }
      var dir = descending_th_class
      if (
        element.className.indexOf(descending_th_class) !== -1 ||
        (table.className.indexOf(ascending_table_sort_class) !== -1 &&
          element.className.indexOf(ascending_th_class) == -1)
      ) {
        dir = ascending_th_class
      }
      reClassify(element, dir)
      var org_tbody = table.tBodies[0]
      var rows = [].slice.call(org_tbody.rows, 0)
      var reverse = dir === ascending_th_class
      rows.sort(function (a, b) {
        var x = getValue((reverse ? a : b).cells[column_index])
        var y = getValue((reverse ? b : a).cells[column_index])
        return isNaN(x - y) ? x.localeCompare(y) : x - y
      })
      var clone_tbody = org_tbody.cloneNode()
      while (rows.length) {
        clone_tbody.appendChild(rows.splice(0, 1)[0])
      }
      table.replaceChild(clone_tbody, org_tbody)
    }
  } catch (error) {
  }
});

Code by Jonas Earendel

HTML

<table class="sortable">
  <thead>
    <tr>
      <th>Head 1</th>
      <th>Head 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Cell 1</td>
      <td>Cell 2</td>
    </tr>
        ...
  </tbody>
</table>

CSS

.sortable th {
   cursor: pointer;
}
.sortable th.no-sort {
   pointer-events: none;
}
.sortable th::after, 
.sortable th::before { transition: color 0.2s ease-in-out; font-size: 1.2em; color: transparent; } .sortable th::after { margin-left: 3px; content: '\025B8'; } .sortable th:hover::after { color: inherit; } .sortable th.dir-d::after { color: inherit; content: '\025BE'; } .sortable th.dir-u::after { color: inherit; content: '\025B4'; }

HTML Table Sorting Methods

A sortable HTML table allows the user to sort the rows by clicking on the column headers. There are different ways to create a sortable HTML table, such as using JavaScript, jQuery plugins or CSS classes. Here are some examples of how to create a sortable HTML table:

Sorting Algorithms

You can build the code for your sortable table using a sorting algorithm that puts elements of a list into order. The order can be numerical, alphabetical, or based on some other criteria. The purpose of sorting is to make the data easier to search, analyze, or display. For example, you can sort a list of names alphabetically or a list of numbers in ascending order.

There are many different sorting algorithms, with different advantages and disadvantages. Some common factors that are used to compare sorting algorithms are:

Some examples of sorting algorithms are:

Sortable Table Generator

The HTML table creator allows you to generator the HTML code for a table. To make a sortable table make sure to activate the header. You'll need to add class="sortable" to the markup, include the attached script and style and you're all set.

2 × 2

Table

Style Name
Georgia
Georgia
Palatino
Times New Roman
Arial
Arial Black
Comic Sans
Impact
Lucida Sans
Tahoma
Trebuchet
Verdana
Courier
Lucida Console
Left Center Right
px
px

Body

Left Center Right

HTML
Preview Apply »
HTML Copy
CSS « Apply