Jquery clone only repeating once. Need to repeat multiple times

Viewed 90

I'm working on some existing code which is in html tables. I need to copy the text from the 'th' header rows and duplicate them inside the corresponding td cells for every subsequent row. I have managed to get the header row to copy but it will only repeat on the first row. How can I get it to repeat on every row that follows? Thanks!

$(document).ready(function() {
  $('.head').each(function(i) {
    var $content = $('.new').eq(i);
    $(this).clone().prependTo($content);
  });
});
table,
tbody,
tr,
th,
td {
  border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table id="table-container">
  <tbody>
    <tr class="header">
      <th class="head">Header 1</th>
      <th class="head">Header 2</th>
      <th class="head">Header 3</th>
      <th class="head">Header 4</th>
    </tr>
    <tr class="row>">
      <td class="new">Row 1</td>
      <td class="new">Row 2</td>
      <td class="new">Row 3</td>
      <td class="new">Row 4</td>
   </tr >
   <tr class="alt>">
      <td class="new">Row 1</td>
      <td class="new">Row 2</td>
      <td class="new">Row 3</td>
      <td class="new">Row 4</td>
    </tr>
  </tbody>
</table>
</div>

1 Answers

Loop over the table rows except the .header one, and then inside loop over the cells of the current row, and prepend the clone of the corresponding .head cell.

$(document).ready(function() {
  $('tr:not(.header)').each(function() {
    $(this).find('.new').each(function(i) {
       $(this).prepend($('.head').eq(i).clone());
    });
  });
});
table,
tbody,
tr,
th,
td {
  border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table id="table-container">
  <tbody>
    <tr class="header">
      <th class="head">Header 1</th>
      <th class="head">Header 2</th>
      <th class="head">Header 3</th>
      <th class="head">Header 4</th>
    </tr>
    <tr class="row>">
      <td class="new">Row 1</td>
      <td class="new">Row 2</td>
      <td class="new">Row 3</td>
      <td class="new">Row 4</td>
   </tr >
   <tr class="alt>">
      <td class="new">Row 1</td>
      <td class="new">Row 2</td>
      <td class="new">Row 3</td>
      <td class="new">Row 4</td>
    </tr>
  </tbody>
</table>
</div>

Related