Jpaji Rajnish
Jpaji Rajnish

Reputation: 1501

Appending to new nodes not yet inserted in the document

In order to make my code concise and reduce unnecessary dom rendering, I'm trying to construct and populate a table before appending it to the document. The problem I'm having is that only the divs are getting appended to the table, so I end up with a table full of divs instead of tr's with td's that contain divs.

I'm pretty sure this is because when I use the .appendTo function it's not appending the td to the tr, and the tr to the table but instead is removing the div and appending it to each in turn, lastly ending up in the table.

How can I construct a node chain before appending to the document?

Code:

    var playerSelect = $( "#playerSelect" );
    var playerElements = [];
    var rowCounter = 0;
    var playerTable = $("<table/>").attr("id", "playerTable");
    for (player in playerBase){
        var playerDiv = $("<div/>").addClass("player").text(player + playerBase[player].rating);
        playerDiv.appendTo("<td/>").appendTo("<tr/>").appendTo(playerTable);                   
    };
    playerSelect.append( playerTable ); 

Upvotes: 1

Views: 31

Answers (2)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

  for (player in playerBase){
var tr = $('<tr/>');
var td = $('<td/>');
     td.appendTo(tr);
        var playerDiv = $("<div/>").addClass("player").text(player + playerBase[player].rating);
        playerDiv.appendTo(td);
       tr.appendTo(playerTable);  
};

Upvotes: 0

tschoffelen
tschoffelen

Reputation: 520

.appendTo() does not accept a string value. $() does however, so you could change your code like this:

$("<tr />").append($("<td />").append(playerDiv)).appendTo(playerTable);

That said, this is not the cleanest way to do it, you might want to have a look at templating engines if you have a lot of these structures in your code.

Upvotes: 3

Related Questions