Alcuinus

table sort

Oct 31st, 2011
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var headers = document.querySelectorAll("th");
  2. for (var i = 0; i < headers.length; i++)
  3.   headers[i].style.cursor = "pointer";
  4.  
  5. for (var j = 0; j < headers.length; j++)
  6. {
  7.     document.querySelectorAll("th")[j].setAttribute("data-index",j);
  8.     document.querySelectorAll("th")[j].onclick = function(){
  9.       var position = Number(this.getAttribute("data-index"));
  10.       var arr = [];
  11.       var nodeList = document.querySelectorAll("tbody tr");
  12.       var parent = nodeList[0].parentNode;
  13.       for(var i = 0; i < nodeList.length; i++) {
  14.         arr.push(nodeList[i]);
  15.         nodeList[i].parentNode.removeChild(nodeList[i])
  16.       }
  17.       arr.sort(function(a,b){
  18.         var aval = a.querySelectorAll("td")[position].innerHTML + " " + a.querySelectorAll("td")[0].innerHTML;
  19.         var bval = b.querySelectorAll("td")[position].innerHTML + " " + b.querySelectorAll("td")[0].innerHTML;
  20.    
  21.         return aval.localeCompare(bval);
  22.       });
  23.       for (var i = 0; i < headers.length; i++)
  24.         if(this !== headers[i])
  25.           headers[i].removeAttribute("data-sortorder");
  26.    
  27.       if (this.getAttribute("data-sortorder") === "asc")
  28.       {
  29.         arr.reverse();
  30.         this.setAttribute("data-sortorder","desc");
  31.       } else {
  32.         this.setAttribute("data-sortorder","asc");
  33.       }
  34.    
  35.       for(var i = 0; i < arr.length; i++) {
  36.         parent.appendChild(arr[i]);
  37.       }
  38.     };
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment