I have a table and need to get it responsive. What I need to do is to take each column’s header’s text to prepend on this column’s body cell by using Jquery.
Problem: I am getting all 3 headers text prepend on all table body cells! ( It should be: CountryAlfreds, but I get CountryContactCompanyAlfreds, for example)
Please take a look at my sample below and direct me how to take each column’s header’s text to prepend on this column’s body cell.
Any help would be appreciated!
$('thead tr th').each( function(e) {
var headerText = $(this).html();
console.log("Header " + headerText);
$(`table tbody tr td`).prepend("<span>" + headerText + "</span>")
})
span {
color: red;
font-weight: 700
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</tbody>
</table>
3
Answers
I’m not sure to have understood correctly, but if this is what you’re looking for, I would suggest putting each column’s cells in the same class:
You need to consider the index of TD as well