lukeseager lukeseager - 1 year ago 87
Javascript Question

Sorting HTML table with JavaScript

I'm after a table sorting solution (in JavaScript) but I can't seem to find a suitable one yet. I just literally need it to sort each column alphabetically. It doesn't need to ignore any code or any numbers or to work with currency. Literally, just a click on the column header switches it from sorted a-z/z-a.

Does anyone know of a really simple solution like this? I can't seem to find one that is simple enough.

Answer Source

I wrote up some code that will sort a table by a row, assuming only one <tbody> and cells don't have a colspan.

function sortTable(table, col, reverse) {
    var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
        tr =, 0), // put rows into array
    reverse = -((+reverse) || -1);
    tr = tr.sort(function (a, b) { // sort rows
        return reverse // `-1 *` if want opposite order
            * (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
    for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
// sortTable(tableNode, columId, false);

If you don't want to make the assumptions above, you'd need to consider how you want to behave in each circumstance. (e.g. put everything into one <tbody> or add up all the preceeding colspan values, etc.)

You could then attach this to each of your tables, e.g. assuming titles are in <thead>

function makeSortable(table) {
    var th = table.tHead, i;
    th && (th = th.rows[0]) && (th = th.cells);
    if (th) i = th.length;
    else return; // if no `<thead>` then do nothing
    while (--i >= 0) (function (i) {
        var dir = 1;
        th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});

function makeAllSortable(parent) {
    parent = parent || document.body;
    var t = parent.getElementsByTagName('table'), i = t.length;
    while (--i >= 0) makeSortable(t[i]);

and then invoking makeAllSortable onload.

Example fiddle of it working on a table.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download