Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a table column with jQuery

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>');
 })
})
like image 389
Mottie Avatar asked Oct 31 '09 19:10

Mottie


People also ask

How do you add a column to a table?

Click in a cell to the left or right of where you want to add a column. Under Table Tools, on the Layout tab, do one of the following: To add a column to the left of the cell, click Insert Left in the Rows and Columns group. To add a column to the right of the cell, click Insert Right in the Rows and Columns group.

How do I add data to a column in HTML?

The following syntax is used to add columns in HTML. <div class="row"> tag is used to initialize the row where all the columns will be added. <div class="column" > tag is used to add the corresponding number of columns. style="background-color:#aaa;" property is used to give color to the column.

How to insert table row in table using JavaScript?

insertRow(tableRef. rows. length); you can simple use tableRef. insertRow(-1); to insert the row at the end of the table.

How to add a new row to a table html?

The HTMLTableElement. insertRow() method inserts a new row ( <tr> ) in a given <table> , and returns a reference to the new row. Note: insertRow() inserts the row directly into the table. The row does not need to be appended separately as would be the case if Document.


2 Answers

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.

like image 93
Dan Herbert Avatar answered Oct 15 '22 18:10

Dan Herbert


$('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.

like image 27
Stefan Kendall Avatar answered Oct 15 '22 18:10

Stefan Kendall