views:

445

answers:

2

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... maybe I need more caffeine.

$(document).ready(function(){
 $('table').find('tr').each(function(){
  $(this).prepend('<td>cell 1a</td>');
 })
})
+2  A: 

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
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
fudgey
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!
fudgey
That's a much better idea. I've changed my answer to include that.
Dan Herbert
+1  A: 
$('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
I tried testing this and it didn't work, but thanks anyway
fudgey
This doesn't work because most, if not all, browsers will wrap all rows around a `<tbody>` 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