Ad

JQuery Thead Object Can't Append Tr Object

- 1 answer

My problem is: I can not append tr objects to thead object, but tfoot works correctly.

There is no error, warning or anything, just in the resulting html code the thead tag will be empty.

var tableObj = $("<table />");
var theadObj = $("<thead />");
var tbodyObj = $("<tbody />");
var tfootObj = $("<tfoot />");

var trObj = $("<tr />");
trObj.append($("<th />").html("colName1"));
trObj.append($("<th />").html("colName2"));
trObj.append($("<th />").html("colName3"));

var trObj2 = $("<tr />");
trObj2.append($("<td />").html("colValue1"));
trObj2.append($("<td />").html("colValue2"));
trObj2.append($("<td />").html("colValue3"));

theadObj.append(trObj); //as you can see in the result, the <thead> will be empty, why?
//theadObj.html('<tr>' + trObj.html() + '</tr>'); //but this works (it so ugly)
            
tfootObj.append(trObj);

tbodyObj.append(trObj2);

tableObj.append(theadObj);
tableObj.append(tbodyObj);
tableObj.append(tfootObj);

$("#test").append(tableObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

If anybody has any idea, please share with me, thanks in advance!

Ad

Answer

In fact you can append it to the thead but your problem here is that you are appending the same object, to the thead then to the tfoot, so the second apppend operation is omitting the first one and the object is moved to the tfoot, that's why you only see it appended to the tfoot.

Here's a snippet showing it appended to the thead only (I commented the code that appends it to the tfoot).

var tableObj = $("<table />");
var theadObj = $("<thead />");
var tbodyObj = $("<tbody />");
var tfootObj = $("<tfoot />");

var trObj = $("<tr />");
trObj.append($("<th />").html("colName1"));
trObj.append($("<th />").html("colName2"));
trObj.append($("<th />").html("colName3"));

var trObj2 = $("<tr />");
trObj2.append($("<td />").html("colValue1"));
trObj2.append($("<td />").html("colValue2"));
trObj2.append($("<td />").html("colValue3"));

theadObj.append(trObj); //as you can see in the result, the <thead> will be empty, why?
//theadObj.html('<tr>' + trObj.html() + '</tr>'); //but this works (it so ugly)
            
//tfootObj.append(trObj);

tbodyObj.append(trObj2);

tableObj.append(theadObj);
tableObj.append(tbodyObj);
tableObj.append(tfootObj);

$("#test").append(tableObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

So in conclusion, an object can only be appended to a single element.

Ad
source: stackoverflow.com
Ad