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>');
})
})
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.
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.
insertRow(tableRef. rows. length); you can simple use tableRef. insertRow(-1); to insert the row at the end of the table.
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.
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.
$('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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With