开发者

How to invert (transpose) the rows and columns of an HTML table?

I want to transpose the开发者_开发百科 rows and columns in an HTML table, i.e. Rows as Columns, Columns as Rows.

In what way I can do it?

Example :

1 4 7  
2 5 8  
3 6 9

as

1 2 3  
4 5 6  
7 8 9  


http://jsfiddle.net/CsgK9/2/

html:

<table>
    <tr>
        <td>1</td>
        <td>4</td>
        <td>7</td>
    </tr>
    <tr>
        <td>2</td>
        <td>5</td>
        <td>8</td>
    </tr>
    <tr>
        <td>3</td>
        <td>6</td>
        <td>9</td>
    </tr>
</table>


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

js:

$("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;
});


There is this a CSS solution by David Bushell (using flexbox): http://dbushell.com/2016/03/04/css-only-responsive-tables/

And there is also this CSS solution (using float)

tr { display: block; float: left; }
th, td { display: block; }

http://jsfiddle.net/XKnKL/3/

(they are both mentioned in this answer: HTML Table with vertical rows)


This should work for arbitrary html:

function swap( cells, x, y ){
   if( x != y ){     
   var $cell1 = cells[y][x];
   var $cell2 = cells[x][y];
   $cell1.replaceWith( $cell2.clone() );
   $cell2.replaceWith( $cell1.clone() );
    }
}

var cells = [];
$('table').find('tr').each(function(){
    var row = [];
    $(this).find('td').each(function(){
       row.push( $(this) );    
    });
    cells.push( row );
});

for( var y = 0; y <= cells.length/2; y++ ){
    for( var x = 0; x < cells[y].length; x++ ){
        swap( cells, x, y );
    }   
}

Working fiddle:

http://jsfiddle.net/Hskke/1/


What language do you want to do it in? I assume JavaScript, as you said jQuery. (jQuery is not a language, it's library to a language)

You need to find a way to represent the table as a data structure. This should be done via OOP for simplicity. I recommend you to get the number of columns and rows and put the data in 1 single, flat array.

You also need to design something that will parses through the HTML and gets the table, converting it to your structure, allowing computations to be done easily. This can be done via jQuery's method.

Then you need to find a sort function that sorts the flat array.

Lastly, you need to break up the the array into the appropriate columns and rows and rerender the HTML.

See! Not that difficult. Designing is pretty much done for you, all you need is to implement it. (Maybe i shouldn't do so much work for you..)


I was looking for a non-jquery way of doing it and came up with this:

const transposeTable = (tbody, newContainerType = "tbody") => {
  const rows = Array.from(tbody.querySelectorAll("tr"))
  const newTbody = document.createElement(newContainerType)

  for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
    const row = rows[rowIdx]
    const cells = Array.from(row.querySelectorAll("td, th"))

    for (let cellIdx = 0; cellIdx < cells.length; cellIdx++ ) {
      const cell = cells[cellIdx]
      const newRow = newTbody.children[cellIdx] || document.createElement("tr")
      if (!newTbody.children[cellIdx]) {
        newTbody.appendChild(newRow)
      }
      newRow.appendChild(cell.cloneNode(true))
    }
  }
  
  // Do live DOM manipulations only once for performance
  tbody.parentElement.appendChild(newTbody)
  tbody.parentElement.removeChild(tbody)
}

transposeTable(document.querySelector("tbody"))

Ref: https://jsfiddle.net/ThomasR/0b9pv1rx/43/


This is @svinto answer with addition of

  • Support for td and th (mixed)
  • ragged tables (those with rows (and columns) of unequal length)

http://jsfiddle.net/xsp4eqwz/2/

$("a#transposeButton").click(function(){
    $("table#transposeThis").each(function() {
        var $this = $(this);
        var newrows = [];
        $this.find("tr").each(function(rowToColIndex){
            $(this).find("td, th").each(function(colToRowIndex){
                if(newrows[colToRowIndex] === undefined) { newrows[colToRowIndex] = $("<tr></tr>"); }
                while(newrows[colToRowIndex].find("td, th").length < rowToColIndex){
                    newrows[colToRowIndex].append($("<td></td>"));
                }
                newrows[colToRowIndex].append($(this));
            });
        });
        $this.find("tr").remove();
        $.each(newrows, function(){
            $this.append(this);
        });
    });
    
    return false;
});
td, th { padding:5px; border:1px solid #ccc;}

th { background-color: silver; font-weight: bold }
<table id="transposeThis">
    <tr>
        <th>H1</th>
        <th>H2</th>
        <th>H3</th>
    </tr>
    <tr>
        <td>1</td>
        <td>4</td>
    </tr>
    <tr>
        <td>2</td>
        <td>5</td>
        <td>8</td>
    </tr>
    <tr>
        <th>H1</th>
        <th>H2</th>
        <th>H3</th>
        <th>H4</th>
    </tr>
    <tr>
        <td>3</td>
        <td>6</td>
        <td>9</td>
        <td>10</td>
    </tr>
</table>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜