How do I add the problem is my table has 1 or 2 th rows? Working version that creates a table from an array What you need to do is remove the rows and append them to a thead element jsFiddle exmaple
use wrapAll instead of wrap and
this using jQuery?
$(\'#myTable tr
function createTable(data) {
var str = "";
str += '<table><thead>';
str += '<tr><td>Pos</td><td>Ref</td></tr></thead><tbody>';
for (var item in data.recentList) {
str += '<tr>';
for (idata in data.recentList[item]) {
str += '<td>' + data.recentList[item][idata] + '</td>';
}
str += '</tr>';
}
str += '</tbody></table>';
$('body').append(str);
}
var myTable = jQuery("#myTable");
var thead = myTable.find("thead");
var thRows = myTable.find("tr:has(th)");
if (thead.length===0){ //if there is no thead element, add one.
thead = jQuery("<thead></thead>").appendTo(myTable);
}
var copy = thRows.clone(true).appendTo("thead");
thRows.remove();
$('#myTable tr:has(th)').wrapAll('<thead></thead>');
$("#myTable thead").prependTo("#myTable")