I want to copy the <th>
contents of a table to the corresponding attributes of the <td>
cells.
My table is like this:
<table>
<thead>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem</td>
<td>lipsum</td>
<td>dolor</td>
</tr>
</tbody>
</table>
This is what I would to achieve:
<table>
<thead>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td data-attr="Heading 1">Lorem</td>
<td data-attr="Heading 2">lipsum</td>
<td data-attr="Heading 3">dolor</td>
</tr>
</tbody>
</table>
I tried with this, but it doesn't work:
var $th = $("thead td");
var $td = $("tbody td")
var $th = $td.closest('table').find('th').eq($td.index());
$td.attr("data-attr", $th);
jsFiddle
In my custom attribute I get data-attr="[object Object]"
insted of th text.
Get the header entries, then for each row, get each td
and use its index to get the text from the matching header entry. There are multiple ways to do this.
Long version:
var $th = $("thead th");
var $tr = $("tbody tr");
$tr.each(function(){
$(this).find('td').each(function(index){
$(this).attr('data-attr', $th.eq(index).text());
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pLdzx6wm/
Another way (slightly faster) is to use the index of the header elements and apply the text to all of the matching columns TDs at once:
var $th = $("thead th");
var $tr = $("tbody tr");
$th.each(function(index){
$tr.find('td:nth-child(' + index + ')').attr('data-attr', $(this).text());
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pLdzx6wm/1/
And lastly, you can use the rather cool jQuery feature that most parameters can be replaced with a callback function to return the value:
var $th = $("thead th");
var $tr = $("tbody tr");
$tr.each(function (index) {
$('td', this).attr('data-attr', function () {
return $th.eq($(this).index()).text();
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pLdzx6wm/3/
Which reduces a bit more to:
var $th = $("thead th");
$('tbody tr td').attr('data-attr', function () {
return $th.eq($(this).index()).text();
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pLdzx6wm/4/
You need to get each td
of each tr
and use th
with same index as td
to get right text.
JSFiddle: http://jsfiddle.net/5ge2et3b/3/
var $th = $("thead th");
var $tr = $("tbody tr");
$tr.each(function(){
var $td = $("td", this);
$td.each(function(i, el){
$(this).attr('data-attr', $th.eq(i).text());
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With