Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert table rows

I want to invert table tbody rows with jQuery.

WHAT I HAVE:

<table width="630" border="0" cellspacing="0" cellpadding="0">
<thead>
 <tr>
    <td>TITLE A</td>
    <td>TITLE B</td>

(...) continue in jsfiddle.

Here what I have and what I want: http://jsfiddle.net/ZaUrP/1/

like image 589
Hugo M. Avatar asked May 22 '13 21:05

Hugo M.


People also ask

Can I invert a table in Excel?

This can be done in two quick steps: With any cell in your table selected, go to the Ablebits Data tab > Transform group, and click Flip > Vertical Flip.

How do I flip columns and rows in Word table?

Select an empty cell below your pasted table. Click the arrow under the "Paste" button on the ribbon and choose the "Transpose" option. Your table will appear flipped.


2 Answers

Try this:-

Get the array of trs from tbody using .get() and use Array.reverse to reverse the elements and assign it back.

var tbody = $('table tbody');
tbody.html($('tr',tbody).get().reverse());

Fiddle

In case you have events to tr or any containing elements you could just attach it using delegation, so that the reversed elements also get them delegated.

Demo

like image 111
PSL Avatar answered Oct 22 '22 00:10

PSL


fiddle

pretty much the same as the other guy, only I use .detach() which is guarunteed to keep any crazy events that were attached to the trs intact. I also use $.makeArray to avoid reversing any of the proto stuff on the base jQuery object.

$(function(){
    $("tbody").each(function(elem,index){
      var arr = $.makeArray($("tr",this).detach());
      arr.reverse();
        $(this).append(arr);
    });
});
like image 42
DefyGravity Avatar answered Oct 22 '22 00:10

DefyGravity