Convert TD columns into TR rows

You want to turn HTML arranged like this:

<tr><td>A</td><td>B</td><td>C</td><td>D</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>

Into this:

<tr><td>A</td><td>1</td></tr>
<tr><td>B</td><td>2</td></tr>
<tr><td>C</td><td>3</td></tr>
<tr><td>D</td><td>4</td></tr>

Correct?

You can do this with Javascript, however, it is difficult to suggest a method with out knowing more about the structure of your site/HTML files. I’ll give it a go.

Assuming your <table> tag comes with an id (like this: <table id="myTable"> you can access it in javascript like this:

var myTable = document.getElementById('myTable');

You can create a new table like this:

var newTable = document.createElement('table');

Now you need to transpose the old tables rows into the new tables columns:

var maxColumns = 0;
// Find the max number of columns
for(var r = 0; r < myTable.rows.length; r++) {
    if(myTable.rows[r].cells.length > maxColumns) {
        maxColumns = myTable.rows[r].cells.length;
    }
}


for(var c = 0; c < maxColumns; c++) {
    newTable.insertRow(c);
    for(var r = 0; r < myTable.rows.length; r++) {
        if(myTable.rows[r].length <= c) {
            newTable.rows[c].insertCell(r);
            newTable.rows[c].cells[r] = '-';
        }
        else {
            newTable.rows[c].insertCell(r);
            newTable.rows[c].cells[r] = myTable.rows[r].cells[c].innerHTML;
        }
    }
}

This ought to do what you need. Be forewarned: not tested. Working this javascript code into an HTML page is left as an exercise for the reader. If anyone spots any errors that I missed, I be gratified if you point them out to me or simply edit to fix 🙂

Leave a Comment