jQuery - add data attribute into table TD by Norlihazmey Ghazali

http://stackoverflow.com/questions/32263081/loop-through-each-tr-and-add-attribute-to-td-with-array-data-from-th/32263237#32263249

HTML

<table class="table demo">
    <tr>
        <th>Table 1</th>
        <th>Table 2</th>
        <th>Table 3</th>
        <th>Table 4</th>
        <th>Table 5</th>
        <th>Table 6</th>
        <th>Table 7</th>
        <th>Table 8</th>
        <th>Table 9</th>
        <th>Table 10</th>
        <th>Table 11</th>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
</table>

CSS

.demo {
	    border:1px solid #C0C0C0;
	    border-collapse:collapse;
	    padding:5px;
	}
	.demo th {
	    border:1px solid #C0C0C0;
	    padding:5px;
	    background:#F0F0F0;
	}
	.demo td {
	    border:1px solid #C0C0C0;
	    padding:5px;
	}

JavaScript

//array to fill with ths
var ths = new Array();

//Clean the text
function trimIt(x) {
    return x.replace(/(^\s+|\s+$)/g, '');
}
//Fill ths array with header text
$(".table th").each(function () {
    var thdatatrimmed = trimIt($(this).html());
    ths.push(thdatatrimmed);
});

//total trs
var trlen = $(".table tr").length;
console.log(trlen);
//add header to data-title attribute to each TD
for (var j = 0; j < trlen; j++) {
    //console.log(ths.length);
    $('.table tr:nth-child('+ (2+j) +')').find('td').each(function(i,v){
         $(this).attr("title", ths[i]);
    });
    
}