Create table with jQuery - append

Mark Fondy picture Mark Fondy · Jan 5, 2012 · Viewed 357.7k times · Source

I have on page div:

<div id="here_table"></div>

and in jquery:

for(i=0;i<3;i++){
    $('#here_table').append( 'result' +  i );
}

this generating for me:

<div id="here_table">
    result1 result2 result3 etc
</div>

I would like receive this in table:

<div id="here_table">
    <table>
          <tr><td>result1</td></tr>
          <tr><td>result2</td></tr>
          <tr><td>result3</td></tr>
    </table>
</div>

I doing:

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

 for(i=0;i<3;i++){
    $('#here_table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

 $('#here_table').append(  '</table>' );

but this generate for me:

<div id="here_table">
    <table> </table> !!!!!!!!!!
          <tr><td>result1</td></tr>
          <tr><td>result2</td></tr>
          <tr><td>result3</td></tr>
</div>

Why? how can i make this correctly?

LIVE: http://jsfiddle.net/n7cyE/

Answer

sransara picture sransara · Jan 5, 2012

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.