Move the cells in the table

Mar 12, 2013 in Javascript

I was recently answering the question on Stackoverflow. The guy was asking how to permute table cells. I thought that it would be pretty interesting as a little challenge...

First of all everybody knows that there are native table methods and object like table.cells and table.rows but who uses them often? I don't. So this is little chance to practice it.

After a while I came up with this code:

function moveCell(row, c1, c2) {
    var cell = row.cells;
        arr = [c1, c2].sort(),
        c1 = arr[1],
        c2 = arr[0];
    row.insertBefore(row.insertBefore(cell[c1], cell[c2]).nextSibling, cell[c1].nextSibling);

var row = $('table tr:nth-child(2)')[0];
moveCell(row, 0, 3);

which will change the positions of the 1st and the 4th cells in the first row.

Function moveCell takes next parameters:

comments powered by Disqus