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/
var table = $('<table>'). addClass('foo'); for(i=0; i<3; i++){ var row = $('<tr>'). addClass('bar'). text('result ' + i); table.
Create Element is the fastest way (check here.): $(document. createElement('table'));
append() / prepend() to Add Table Row in jQuery. To add a row in the table body using jQuery, we can use DOM inside insertion methods of append() or prepend() that adds an element to the suggested element's start or end. Here we will select the tbody element of table element with id="test" to add a row after it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With