Web / HTML Interview questions
How do I invert/transpose the rows and columns of a HTML table?
Save the below content into a file with .html extension and open it in browser.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <html> <head> </head> <script> $( document ).ready(function() { $("#tableID").each(function() { var $this = $(this); var newTransposedRow = []; $this.find("tr").each(function(){ var i = 0; $(this).find("td").each(function(){ i++; if(newTransposedRow[i] === undefined) { newTransposedRow[i] = $("<tr></tr>"); } newTransposedRow[i].append($(this)); }); }); $this.find("tr").remove(); $.each(newTransposedRow, function(){ $this.append(this); }); }); }); </script> <body> <table id="tableID"> <tr> <td>R1C1</td> <td>R1C2</td> <td>R1C3</td> </tr> <tr> <td>R2C1</td> <td>R2C2</td> <td>R2C3</td> </tr> </table> </body> </html>
More Related questions...