Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add table row before or after a table row of known ID

In a table like this:

<table>
<!-- Insert Row of bun here -->
  <tr id="meat">
   <td>Hamburger</td>
  </tr>
<!-- Insert Row of bun here -->
</table>

function AddBefore(rowId){}
function AddAfter(rowId){}

I need to create methods without using jQuery.. I am familiar with append after and append before in jQuery.. but I am stuck with using plain js.

like image 237
Perpetualcoder Avatar asked Dec 23 '10 01:12

Perpetualcoder


People also ask

How do you add a row to a table?

Add a row above or below Click in a cell above or below where you want to add a row. Under Table Tools, on the Layout tab, do one of the following: To add a row above the cell, click Insert Above in the Rows and Columns group. To add a row below the cell, click Insert Below in the Rows and Columns group.

Which tag is used to add data in row to tables?

To add data to a table, create a row and use the “td” tag to insert data inside each row.

How do you insert new row at a certain index in a table in jQuery?

The task is to insert a new row in that table at a certain index using JQuery. Approach: Store the table column value <td> element into the variable. Then use eq() and after() method to insert the row in a table.


2 Answers

Use

function AddBefore(rowId){
    var target = document.getElementById(rowId);
    var newElement = document.createElement('tr');
    target.parentNode.insertBefore(newElement, target);
    return newElement;
}

function AddAfter(rowId){
    var target = document.getElementById(rowId);
    var newElement = document.createElement('tr');

    target.parentNode.insertBefore(newElement, target.nextSibling );
    return newElement;
}
like image 164
Gabriele Petrioli Avatar answered Nov 05 '22 14:11

Gabriele Petrioli


You want insertBefore. Use with nextSibling to insert after a known element.

like image 33
Phrogz Avatar answered Nov 05 '22 15:11

Phrogz