Jquery insert new row into table at a certain index
Try this:
var i = 3;
$('#my_table > tbody > tr:eq(' + i + ')').after(html);
or this:
var i = 3;
$('#my_table > tbody > tr').eq( i ).after(html);
or this:
var i = 4;
$('#my_table > tbody > tr:nth-child(' + i + ')').after(html);
All of these will place the row in the same position. nth-child
uses a 1 based index.
You can use .eq()
and .after()
like this:
$('#my_table > tbody > tr').eq(i-1).after(html);
The indexes are 0 based, so to be the 4th row, you need i-1
, since .eq(3)
would be the 4th row, you need to go back to the 3rd row (2
) and insert .after()
that.
Note:
$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody
$("table#myTable tr").last().after(newRow); // this will add new row outside tbody
//i.e. between thead and tbody
//.before() will also work similar