How to transpose an HTML table?

18,722

try this code

<style>
td { padding:5px; border:1px solid #ccc;}
</style>
<script>
$("a").click(function(){
    $("table").each(function() {
        var $this = $(this);
        var newrows = [];
        $this.find("tr").each(function(){
            var i = 0;
            $(this).find("td").each(function(){
                i++;
                if(newrows[i] === undefined) { newrows[i] = $("<tr></tr>"); }
                newrows[i].append($(this));
            });
        });
        $this.find("tr").remove();
        $.each(newrows, function(){
            $this.append(this);
        });
    });

    return false;
});

</script>
<table>
    <tr>
        <td>Heading1</td>
        <td>Heading2</td>
        <td>Heading3</td>
    </tr>

    <tr>
        <td>data</td>
        <td>data</td>
        <td>data</td>
    </tr>
</table>


<p><a href="#">Do it.</a></p>

don't forgot to link necessary (jquery1.6) file and appropriate html tags.

try give link http://jsfiddle.net/CsgK9/2/

see this link for original view https://stackoverflow.com/a/6298066

Share:
18,722
GCallie
Author by

GCallie

Updated on June 04, 2022

Comments

  • GCallie
    GCallie almost 2 years

    Is there a way (I don't know the right word for it) to twist a table with jQuery? With a function or something?

    For example I have an table like this:

    <table>
        <tr>
            <th></th>
            <th></th>
            <th></th>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </table>
    

    Table1

    And I want it like this:

    <table>
        <tr>
            <th></th>
            <td></td>
        </tr>
        <tr>
            <th></th>
            <td></td>
        </tr>
        <tr>
            <th></th>
            <td></td>
        </tr>
    </table>
    

    enter image description here

  • zhirzh
    zhirzh almost 9 years
    when re-posting a solution, please give credit to the original one: stackoverflow.com/a/6298066