Advertisement
rg443

html table sort

Jun 18th, 2018
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. function sortTable(table, col, reverse) {
  3.     var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
  4.         tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
  5.         i;
  6.     reverse = -((+reverse) || -1);
  7.     tr = tr.sort(function (a, b) { // sort rows
  8.         return reverse // `-1 *` if want opposite order
  9.             * (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
  10.                 .localeCompare(b.cells[col].textContent.trim())
  11.                );
  12.     });
  13.     for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
  14. }
  15. // sortTable(tableNode, columId, false);
  16.  
  17.  
  18. function makeSortable(table) {
  19.     var th = table.tHead, i;
  20.     th && (th = th.rows[0]) && (th = th.cells);
  21.     if (th) i = th.length;
  22.     else return; // if no `<thead>` then do nothing
  23.     while (--i >= 0) (function (i) {
  24.         var dir = 1;
  25.         th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
  26.     }(i));
  27. }
  28.  
  29. function makeAllSortable(parent) {
  30.     parent = parent || document.body;
  31.     var t = parent.getElementsByTagName('table'), i = t.length;
  32.     while (--i >= 0) makeSortable(t[i]);
  33. }
  34.  
  35. // https://stackoverflow.com/questions/14267781/sorting-html-table-with-javascript
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement