Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
Get prepend() dynamically

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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!