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:
- Using JavaScript: You can use a function that compares the values of two cells and swaps them if needed. In our example we added an event listener to the table headers that calls the function when clicked. For example, you can use our code to sort a table by name or country.
- Using jQuery plugins: You can use a plugin that provides sorting functionality for HTML tables. You need to include the plugin script and apply it to your table element.
- Using CSS classes: You can use a class that adds sorting functionality to your table element, such as sortable, in our example. You need to include the class script and add the class name to your table element.
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:
- Computational complexity: How fast the algorithm runs in terms of the size of the list. For example, some algorithms run faster when the list is already sorted or nearly sorted, while others run slower when the list is in reverse order.
- Memory usage: How much extra space the algorithm needs to store temporary data. For example, some algorithms sort the list in place, meaning they do not need any extra space, while others create a new sorted list and copy the data over.
- Stability: Whether the algorithm preserves the relative order of elements that have the same value. For example, if you sort a list of students by their grades, a stable algorithm will keep the original order of students who have the same grade, while an unstable algorithm may change it.
Some examples of sorting algorithms are:
- Selection sort: This algorithm finds the smallest element in the list and swaps it with the first element, then finds the second smallest element and swaps it with the second element, and so on until the list is sorted. This algorithm is simple but slow, as it always takes n^2 steps to sort a list of n elements.
- Bubble sort: This algorithm compares adjacent elements in the list and swaps them if they are out of order, then repeats this process until no more swaps are needed. This algorithm is also simple but slow, as it can take up to n^2 steps to sort a list of n elements. However, it can be faster if the list is already sorted or nearly sorted.
- Insertion sort: This algorithm builds a sorted list one element at a time by inserting each element into its correct position in the sorted list. This algorithm is efficient for small lists or lists that are already sorted or nearly sorted, as it can take only n steps to sort a list of n elements in the best case. However, it can be slow for large or unsorted lists, as it can take up to n^2 steps in the worst case.
- Merge sort: This algorithm divides the list into two halves, recursively sorts each half using merge sort, then merges the two sorted halves into one sorted list. This algorithm is fast and stable, as it always takes n log n steps to sort a list of n elements. However, it requires extra space to store the temporary lists during merging.
- Quick sort: Quick sort algorithm chooses a pivot element from the list, partitions the list into two sublists such that all elements less than or equal to the pivot are in one sublist and all elements greater than the pivot are in another sublist, then recursively sorts each sublist using quick sort. This algorithm is fast and does not require extra space, as it sorts the list in place. However, it is unstable and its performance depends on how well the pivot is chosen. In the best case, it takes n log n steps to sort a list of n elements. In the worst case, it takes n^2 steps.
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.