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.
Asked
Active
Viewed 4,504 times
2

Felix Kling
- 795,719
- 175
- 1,089
- 1,143

Prasanna
- 2,593
- 7
- 39
- 53
-
possible duplicate of [javascript: how to append div in "begining" of another div](http://stackoverflow.com/questions/15110484/javascript-how-to-append-div-in-begining-of-another-div) – Felix Kling Aug 16 '13 at 09:33
7 Answers
3
In Vanilla JavaScript, it really is as simple as:
var firstRow = yourTable.rows[0];
firstRow.parentNode.insertBefore(newRow,firstRow);

Niet the Dark Absol
- 320,036
- 81
- 464
- 592
3
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

Dhaval Bharadva
- 3,053
- 2
- 24
- 35
1
Use .prepend
$("#tableId tbody").prepend("tr code here");

Suresh Atta
- 120,458
- 37
- 198
- 307

Tushar Gupta - curioustushar
- 58,085
- 24
- 103
- 107
0
You could use something like this:
$('table > tbody > tr:first').before('<tr>...</tr>');

dotnethaggis
- 1,000
- 12
- 26
0
Use the .prepend()
method. This function do exactly what you need.

Tushar Gupta - curioustushar
- 58,085
- 24
- 103
- 107

Apalabrados
- 1,098
- 8
- 21
- 38
0
Try this:
<table id="tblTest">
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Add" id="btnAdd"></input></td>
</tr>
</table>
var row = $("#tblTest tbody").html();
$("#btnAdd").click(function(){
$("#tblTest tbody").prepend(row);
});

Abhishek Jain
- 2,597
- 1
- 18
- 12