Create table with jQuery – append

This line:

$('#here_table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );

Appends to the div#here_table not the new table.

There are several approaches:

/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
    content += '<tr><td>' + 'result ' +  i + '</td></tr>';
}
content += "</table>"

$('#here_table').append(content);

But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.

But how about this one, it does what you expect nearly great:

var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
    var row = $('<tr>').addClass('bar').text('result ' + i);
    table.append(row);
}

$('#here_table').append(table);

Hope this would help.

Leave a Comment