Invert Line Strings

I want to invert the tbody rows table using 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 is what I have and what I want: http://jsfiddle.net/ZaUrP/1/

+6
source share
4 answers

fiddle

pretty much the same as the other guy, only I use .detach (), which is guaranteed to keep any crazy events that were bound to tr intact. I also use $ .makeArray to avoid changing any proto element on the jQuery base object.

 $(function(){ $("tbody").each(function(elem,index){ var arr = $.makeArray($("tr",this).detach()); arr.reverse(); $(this).append(arr); }); }); 
+21
source

Try the following: -

Get the tr array from tbody using .get() and use Array.reverse to undo the elements and assign them back.

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

Fiddle

If you have events before tr or any containing elements, you can simply attach it using delegation, so that inverse elements will also be delegated to them.

Demo

+7
source
 $('tbody').each(function(){ var list = $(this).children('tr'); $(this).html(list.get().reverse()) }); 

Demo --> http://jsfiddle.net/ZaUrP/5/

+3
source

I wrote a jQuery plugin called $.reverseChildren that will undo all the specified children of this element. Credit goes to DefyGravity for its insightful and intriguing use of $.makeArray .

I not only turned the rows of the table, but also the columns.

 (function($) { $.fn.reverseChildren = function(childSelector) { this.each(function(el, index) { var children = $.makeArray($(childSelector, this).detach()); children.reverse(); $(this).append(children); }); return this; }; }(jQuery)); $(function() { var tableCopy = $('#myTable').clone(true).attr('id', 'myTableCopy').appendTo( $('body').append('<hr>').append($('<h1>').html('Reversed Table'))); tableCopy.find('tr').reverseChildren('th, td'); // Reverse table columns tableCopy.find('tbody').reverseChildren('tr'); // Reverse table rows }); 
 * { font-family: "Helvetica Neue", Helvetica, Arial; } h1 { font-size: 16px; text-align: center; } table { margin: 0 auto; } th { background: #CCC; padding: 0.25em; } td { border: 1px solid #CCC; padding: 5px; } hr { margin: 12px 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h1>Original Table</h1> <table id="myTable" width="320" border="0" cellspacing="0" cellpadding="0"> <thead> <tr> <th>Header A</th> <th>Header B</th> <th>Header C</th> </tr> </thead> <tbody> <tr> <td>Data 1A</td> <td>Data 1B</td> <td>Data 1C</td> </tr> <tr> <td>Data 2A</td> <td>Data 2B</td> <td>Data 2C</td> </tr> <tr> <td>Data 3A</td> <td>Data 3B</td> <td>Data 3C</td> </tr> <tr> <td>Data 4A</td> <td>Data 4B</td> <td>Data 4C</td> </tr> </tbody> </table> 
+1
source

Source: https://habr.com/ru/post/945633/


All Articles