I need to split a table into two tables at a particular row number using jQuery. Can this be done?
I googled but couldn\'t find anything. jQuery\'s pretty powerful,
jQuery Slice method will be useful in such case: documentation here
Add a table with some rows in html:
<table id="mainTable">
<tr>
<td>Row 1</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 2</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 3</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 4</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 5</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 6</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 7</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 8</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 9</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 10</td>
<td>Dummy Data</td>
</tr>
</table>
Slice n rows using jQuery, create new table instance and append rows:
<script type="text/javascript">
jQuery(document).ready(function() {
var $mainTable = $("#mainTable");
var splitBy = 5;
var rows = $mainTable.find ( "tr" ).slice( splitBy );
var $secondTable = $("#mainTable").parent().append("<table id='secondTable'><tbody></tbody></table>");
$secondTable.find("tbody").append(rows);
$mainTable.find ( "tr" ).slice( splitBy ).remove();
});
</script>
See working demo here
This can also be done with clone()
var $mainTable = $("table.mainTable");
$mainTable.clone().appendTo($mainTable.parent()).find('tbody tr').slice(0, 4).remove();
$mainTable.find('tbody tr').slice(4).remove();