sammiwei
sammiwei

Reputation: 3200

How to append multiple table cells using jQuery

jq('#table1') 
  .append(jq('<tr>') 
    .append(jq('<td>') 
      .append('data1' 
      ) 
    ) 
  ); 

I want to append more than one <td> to my current <tr>, each of these <td> has different format, so I can not just use a for loop to create bunch of <td>. The ( ) in this case is very tricky, anybody got an idea how this might work?

By each of these <td> has different format, I mean that I need to add $ to some of the cells that representing money, etc.

Upvotes: 2

Views: 6444

Answers (4)

Steve
Steve

Reputation: 8640

jq('#table1').append(
    jq('<tr>')
        .append(jq('<td>').append('data1')) 
        .append(jq('<td>').append('data2')) 
        .append(jq('<td>').append('data3')) 
);

EDIT: Corrected to append tds, not data in tds

Upvotes: 3

sammiwei
sammiwei

Reputation: 3200

  jq('#table1') 
  .append(jq('<tr>') 
    .append(jq('<td>').append('data1')) 
    .append(jq('<td>').append('data1')) 
    .append(jq('<td>').append('data2')) 
    .append(jq('<td>').append('data3'))     
  ); 

Upvotes: 1

Taha Paksu
Taha Paksu

Reputation: 15616

jq("#table1").append("<tr></tr>"); 

then;

jq("#table1 tr:last").append("<td></td>");
jq("#table1 tr:last").append("<td></td>");
jq("#table1 tr:last").append("<td></td>");
jq("#table1 tr:last").append("<td></td>");

will append 4 td's to your last added tr.

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

Create the markup first and append everything at last for best performance:

var tds = [
    '<td>...</td>',
    '<td>...</td>',
    '<td>...</td>'
];

$('#table').append('<tr>' + tds.join('') + '</tr>');

Upvotes: 1

Related Questions