Created
October 12, 2016 15:24
-
-
Save ceving/f0c2783689fa0c08a1c6e37be1aba062 to your computer and use it in GitHub Desktop.
Very basic and simple table sorter in plain JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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