Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table with jQuery - append

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/

like image 609
Mark Fondy Avatar asked Jan 05 '12 20:01

Mark Fondy


People also ask

How to create table element in jQuery?

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

How to create HTML table in jQuery?

Create Element is the fastest way (check here.): $(document. createElement('table'));

How can we append the first row in a table using jQuery?

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.


1 Answers

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.

like image 183
sransara Avatar answered Oct 07 '22 21:10

sransara