Home > other >  Get prepend() dynamically
Get prepend() dynamically

Time:04-11

I have a table generated in a backend. My task is to wrap text in each header column and add it to each body column cells by using .html() and .prepend(). It works as expected (you will see text in green).

Problem: Tables are generated in a backend, sometimes a table has 3 columns, sometimes 4 columns or more! How to write my Jquery dynamically in order to work on each table.

Please give me a hand. Thanks!

$(document).ready(function() {
  var firstHead = $("table thead tr th:first-child").html();
  var firstBodyCode = $("<span></span>").text(firstHead);
  $('table tbody tr td:first-child').prepend(firstBodyCode);

  var secondHead = $("table thead tr th:nth-child(2)").html();
  var secondBodyCode = $("<span></span>").text(secondHead);
  $('table tbody tr td:nth-child(2)').prepend(secondBodyCode);
});
table {
  width: 100%;
  border: 1px solid gray
}

span {
  color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

CodePudding user response:

Use a loop to iterate over all the columns.

$(document).ready(function() {
  $("table thead tr th").each(function(i) {
    let bodyCode = $("<span>", {
      text: $(this).text()
    });
    $(`table tbody tr td:nth-child(${i 1})`).prepend(bodyCode);
  });
});
table {
  width: 100%;
  border: 1px solid gray
}

span {
  color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

  • Related