divide a table

divide a table

I want to divide a table to two new table, this is my way, and hope the code can be more brief.

Script
  1. $(function() {
  2. var $devide = 2,
  3. $newTableWidth1 = 0,
  4. $newTableWidth2 = 0,
  5. $newTableStr1 = '<table id="newTable1">',
  6. $newTableStr2 = '<table id="newTable2">';
  7. $('table tr').each(function($i) {
  8. $newTableStr1 += $(this).is('[class]') ? '<tr class="' + $(this).attr('class') + '">' : '<tr>';
  9. $newTableStr2 += $(this).is('[class]') ? '<tr class="' + $(this).attr('class') + '">' : '<tr>';
  10. $(this).find('td').each(function() {
  11. // get new table 1 width
  12. if ($i == 0) {
  13. if ($(this).index() < $devide) {
  14. $newTableWidth1 += $(this).outerWidth();
  15. } else {
  16. $newTableWidth2 += $(this).outerWidth();
  17. }
  18. }
  19. // new table 1
  20. if ($(this).index() < $devide) {
  21. $newTableStr1 += $(this).is('[class]') ? '<td class="' + $(this).attr('class') + '">' + $(this).html() + '</td>' : '<td>' + $(this).html() + '</td>';
  22. } else {
  23. $newTableStr2 += $(this).is('[class]') ? '<td class="' + $(this).attr('class') + '">' + $(this).html() + '</td>' : '<td>' + $(this).html() + '</td>';
  24. }
  25. });
  26. $newTableStr1 += '</tr>';
  27. $newTableStr2 += '</tr>';
  28. });
  29. $newTableStr1 += '</table>';
  30. $newTableStr2 += '</table>';
  31. $('body').append($newTableStr1).append($newTableStr2);
  32. $('#newTable1').width($newTableWidth1);
  33. $('#newTable2').width($newTableWidth2);
  34. });

CSS
  1. <style>
  2. body {
  3. font-size: 12px;
  4. }
  5. table {
  6. border-collapse: collapse;
  7. margin: 4px 0;
  8. }
  9. tr, td {
  10. text-align: center;
  11. border: 1px solid black;
  12. }
  13. td {
  14. padding: 4px;
  15. }
  16. .yellow {
  17. background: yellow;
  18. }
  19. .gray {
  20. background: gray;
  21. }
  22. </style>

HTML
  1. <table width="400" border="0" cellspacing="0" cellpadding="0">
  2.     <tr>
  3.         <td>a</td>
  4.         <td>b</td>
  5.         <td>c</td>
  6.         <td>d</td>
  7.         <td>e</td>
  8.     </tr>
  9.     <tr>
  10.         <td>1</td>
  11.         <td>2</td>
  12.         <td class="gray">3</td>
  13.         <td>4</td>
  14.         <td>5</td>
  15.     </tr>
  16.     <tr class="yellow">
  17.         <td>6</td>
  18.         <td>7</td>
  19.         <td>8</td>
  20.         <td>9</td>
  21.         <td>10</td>
  22.     </tr>
  23.     <tr>
  24.         <td>11</td>
  25.         <td class="gray">12</td>
  26.         <td>13</td>
  27.         <td>14</td>
  28.         <td>15</td>
  29.     </tr>
  30.     <tr>
  31.         <td>16</td>
  32.         <td>17</td>
  33.         <td>18</td>
  34.         <td>19</td>
  35.         <td>20</td>
  36.     </tr>
  37. </table>