How to sort an existing table in greasemonkey?

I am writing greasemonkey user.js for a page with a table in it. (The table is 100 rows in 18 columns.) Now, what I want to do is make it sort by column, and also run it in both Chrome and Firefox.

All searches for answers so far have led to suggestions to use jquery / dojo or something similar.

Is it possible to do without external code? Ofter all this is just a matter of replacing the string in a different order, right? or is it a stupid thing to say?

The fact is that I already use dojo for some queries, but since I want it to run in both Firefox and Chrome, I just copied the whole dojo thing into my script ..

In addition, most of the solutions I have found so far seem to be more suitable for creating a table, rather than modifying an existing one.

Any help is appreciated.

EDIT: all cells in the table contain numbers.

+5
source share
2 answers

The smart way is to use a tool like tablesorter .
But, since you do not want to use external code (at the moment), this can be difficult.

Here's how to make it a semi-hard way. Note that I'm AM using jQuery. You would be wise to include at least this in your script.

// @require. GM script Chrome, Tampermonkey.
( jQuery GM- Chrome.)

, : :

//--- Get the table we want to sort.
var jTableToSort    = $("table#myTable");

//--- Get the rows to sort, but skip the first row, since it contains column titles.
var jRowsToSort     = jTableToSort.find ("tr:gt(0)");

//--- Sort the rows in place.
jRowsToSort.sort (SortByFirstColumnTextAscending).appendTo (jTableToSort);

function SortByFirstColumnTextAscending (zA, zB)
{
     var ValA_Text  = $(zA).find ("td:eq(0)").text ();
     var ValB_Text  = $(zB).find ("td:eq(0)").text ();

     if      (ValA_Text  >  ValB_Text)
        return 1;
     else if (ValA_Text  <  ValB_Text)
        return -1;
     else
        return 0;
}


jsFiddle.


:

, , :

function SortBy2ndColumnNumber (zA, zB)
{
   var ValA = parseFloat ($(zA).find ("td:eq(1)").text () );
   var ValB = parseFloat ($(zB).find ("td:eq(1)").text () );

   return ValA - ValB;
}

. jsFiddle.

+3

" - , ", . . :

  • IE, Array.prototype.slice.call.

getRowValue, # 1 , .

function sortTable(table, col) {
  var rows = Array.prototype.slice.call(table.getElementsByTagName('tr'), 0);
  rows.sort(function(a,b) {
    return getRowValue(a, col) - getRowValue(b, col);
  });

  for (var i=0, row; row = rows[i]; i++) {
    table.appendChild(row);
  }

  function getRowValue(row, col) {
    return parseInt(row.cells[col].innerHTML, 10);
  }
}​

DEMO: http://jsbin.com/akexe4

+2

All Articles