Skip to content

Instantly share code, notes, and snippets.

@ceving
Created October 12, 2016 15:24
Show Gist options
  • Save ceving/f0c2783689fa0c08a1c6e37be1aba062 to your computer and use it in GitHub Desktop.
Save ceving/f0c2783689fa0c08a1c6e37be1aba062 to your computer and use it in GitHub Desktop.
Very basic and simple table sorter in plain JavaScript
// Sort the rows of a table body by the given column.
function sorttable (table, column) {
var trs = [];
var tbody = table.querySelector ('tbody');
for (var tr of tbody.querySelectorAll ('tr')) {
trs.push(tr.cloneNode(true));
tbody.removeChild(tr);
}
trs.sort(function(r1 ,r2) {
var c1 = r1.querySelectorAll('td').item(column).innerText;
var c2 = r2.querySelectorAll('td').item(column).innerText;
if (c1 > c2) return 1;
if (c1 < c2) return -1;
return 0;
});
trs.forEach(tbody.appendChild.bind(tbody));
}
// For the table with the given id make the header elements of a header
// row having the "sortable" class clickable, in order to sort the table
// by the corresponding column.
function sortable (id) {
var table = document.getElementById(id);
for (var th of table.querySelectorAll('thead tr.sortable th')) {
th.onclick = function (ev) {
sorttable (table, ev.target.cellIndex);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment