I have a table with 12 columns. Each column would have a text box. When I click on an 'Add' button, a new row should be inserted above the first row of the table. How would I do it? Say, if I use jquery append(), it would only add the row at the end but I want to add at the top of the first row.
I have a table with 12 columns. Each column would have a text box. When I click on an 'Add' button, a new row should be inserted above the first row of the table. How would I do it? Say, if I use jquery append(), it would only add the row at the end but I want to add at the top of the first row.
javascript
jquery
dom
Share
Improve this question
edited Aug 16, 2013 at 9:34
Felix Kling
818k181181 gold badges1.1k1.1k silver badges1.2k1.2k bronze badges
asked Aug 16, 2013 at 9:29
PrasannaPrasanna2,66199 gold badges4242 silver badges5454 bronze badges1
possible duplicate of javascript: how to append div in "begining" of another div
– Felix Kling
CommentedAug 16, 2013 at 9:33
Add a ment
|
8 Answers
8
Reset to default
6
Try
$("#tableId tbody").prepend("<tr>..</tr>");
In Vanilla JavaScript, it really is as simple as:
var firstRow = yourTable.rows[0];
firstRow.parentNode.insertBefore(newRow,firstRow);
You can use following alternatives for that
1) .before() for documentations click here
2) .insertBefore() for documentations click here
3) .prepend() for documentations click here
Use the .prepend() method. This function do exactly what you need.
In Vanilla JavaScript, to add a new row at the top of a table is as simple as:
const table = document.getElementById("myTable");
var row = myTable.insertRow(1); // Give index as 1
var cell1= row.insertCell(0);
var cell2= row.insertCell(1);
cell1.innerHTML = "Contents in cell1";
cell2.innerHTML = "Contents in cell2";