Skip to content Skip to sidebar Skip to footer

How Can I Copy The Corresponding Table Header (th) To Their Table Cell (td)?

I want to copy the contents of a table to the corresponding attributes of the cells. My table is like this:

Solution 1:

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/

Solution 2:

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());
    });
});

Solution 3:

The reason you are getting that is because you are trying to append the jQuery object and not the text inside the element.

This is another way to do it

var $th = $("thead th");
var $td = $("tbody td");

$td.attr('data-attr', function(){
    return $th.eq($(this).index()).text();
});

Solution 4:

if you have multiple tables on the same page the accepted answer will use the attributes of the first table for all other tables also. if you want to ensure each table uses its own attributes:

$("table").each(function () {
    var $th = $("thead tr th", this);
    $('tbody tr td', this).attr('data-attr', function () {
        return $th.eq($(this).index()).text();
    });
});

didn't have enough points to post this as a comment to the excellent accepted answer.

Post a Comment for "How Can I Copy The Corresponding Table Header (th) To Their Table Cell (td)?"