I am faced with the challenge of wrapping text in each header column of a table generated in a backend, and adding it to each body column cell using .html() and .prepend(). The expected result is that the text will appear in green.
However, the problem arises when there are two independent tables on a page. The green text in the first table displays correctly, but the header text from the first table gets added to the body column cells of the second table, causing a messy layout as shown in the image below: https://i.sstatic.net/BssZ5.jpg
The desired layout for the two tables should resemble the image below: https://i.sstatic.net/qSKmF.jpg
I am seeking guidance on how to resolve this issue. Any help would be greatly appreciated. Thanks
$(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>
<p>
<table>
<thead>
<tr>
<th>Day</th>
<th>Earn</th>
</tr>
</thead>
<tbody>
<tr>
<td>Monday</td>
<td>$100</td>
</tr>
<tr>
<td>Tuesday</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
</p>
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
<td>$200</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
<td>$180</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>