Reputation: 35256
I have a table that looks something like this:
<table><tbody>
<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>
<tr><td>e</td><td>5</td></tr>
<tr><td>f</td><td>6</td></tr>
<tr><td>g</td><td>7</td></tr>
</tbody></table>
I need it to get to something like this:
<table><tbody>
<tr>
<td>a</td><td>b</td><td>c</td><td>d</td>
<td>e</td><td>f</td><td>g</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td>
<td>5</td><td>6</td><td>7</td>
</tr>
</tbody></table>
I'm open to Javascript, jQuery or even CSS for this.
Upvotes: 3
Views: 5149
Reputation: 11834
I have a jquery class that accomplish this task. This class supports rowspan and colspan in the table as well.
Usage is really simple:
$('#newtable').tableflip($('#sourcetable'));
Here is the code of the class and sample usage: https://jsfiddle.net/adyhu78/9b1q4ys0/
Upvotes: 1
Reputation: 684
Here is my solution: http://jsfiddle.net/mtrwk/19/
$('table').each(function() {
$(this).after("<table><tbody></tbody></table>");
var newTable = $(this).next("table").children("tbody");
$(this).children("tbody").children("tr").each(function(rIndex, rItem){
$(this).children("td").each(function(dIndex, dItem){
if(newTable.children("tr:eq("+dIndex+")").html() == null){
newTable.append("<tr></tr>");
}
newTable.children("tr:eq("+dIndex+")").append($(this)[0].outerHTML);
});
});
});
Upvotes: 2
Reputation: 104760
This will swap the rows and columns of any size tbody, as long as rows all have the same number of cells.
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> Small Test Page</title>
</head>
<body>
<script>
function tableSwap(){
var t= document.getElementsByTagName('tbody')[0],
r= t.getElementsByTagName('tr'),
cols= r.length, rows= r[0].getElementsByTagName('td').length,
cell, next, tem, i= 0, tbod= document.createElement('tbody');
while(i<rows){
cell= 0;
tem= document.createElement('tr');
while(cell<cols){
next= r[cell++].getElementsByTagName('td')[0];
tem.appendChild(next);
}
tbod.appendChild(tem);
++i;
}
t.parentNode.replaceChild(tbod, t);
}
</script>
<h1> Small Test Page</h1>
<p> <button type= "button" id= "tableSwapBtn" onclick= "tableSwap()">
Swap rows and columns</button> </p>
<table style="width:300px;border:1px" rules="all">
<tbody>
<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>
<tr> <td> e</td> <td> 5</td> </tr>
<tr> <td> f</td> <td> 6</td> </tr>
<tr> <td> g</td> <td> 7</td> </tr>
</tbody>
</table>
</body>
</html>
Upvotes: 2