13

I have a table of data that I need to dynamically add a column to. Lets say I have this basic table to start with:

<table>
 <tr><td>cell 1</td><td>cell 2</td><td>cell 3</td></tr>
 <tr><td>cell 1</td><td>cell 2</td><td>cell 3</td></tr>
 <tr><td>cell 1</td><td>cell 2</td><td>cell 3</td></tr>
</table>

I would like to insert a column between cell 1 and cell 2 in each row... I've tried this but it just isn't working like I expect...

$(document).ready(function(){
 $('table').find('tr').each(function(){
  $(this).prepend('<td>cell 1a</td>');
 })
})
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mottie
  • 84,355
  • 30
  • 126
  • 241

3 Answers3

28

Try this:

$(document).ready(function(){
    $('table').find('tr').each(function(){
        $(this).find('td').eq(0).after('<td>cell 1a</td>');
    });
});

Your original code would add the column to the end of each row, not in between columns. This finds the first column and adds the cell next to the first column.

Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
  • Nice thanks, this worked perfectly!... *smacks head* I should have looked for the cell and placed it after. I really do need some caffeine LOL – Mottie Oct 31 '09 at 19:29
  • I actually ended up using `td:eq(0)` because there will be times when I need to insert a column into the middle of a table with more then 3 columns, then all I need to do is change the variable... thanks again for the help! – Mottie Oct 31 '09 at 19:57
  • That's a much better idea. I've changed my answer to include that. – Dan Herbert Oct 31 '09 at 20:12
  • Just a heads up, just watch for columns if you have to insert somewhere in the middle of the table, you may have to account for td's that have colspan. – Sam Plus Plus Jul 25 '14 at 19:01
2
$('table > tr > td:first-child').after( '<td>cell 1a</td>' );

tr > td selects the first-level td after a tr, and after inserts data outside the element.

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
  • 2
    This doesn't work because most, if not all, browsers will wrap all rows around a `` tag, so the selector would need to be "`table > tbody > tr > td:first-child`". Of course that may be a somewhat slow query to perform since jQuery would have to do a lot of filtering to get all cells in a big table... – Dan Herbert Oct 31 '09 at 19:33
0
$('td:first-child').after('&lt;td&gt;new cell&lt;/td&gt;');
Undo
  • 25,519
  • 37
  • 106
  • 129
Jackie
  • 25,199
  • 6
  • 33
  • 24