If you are using jQuery then use .after()
with :eq(int)
and for removing you can use .remove()
but if you want to remove only newly added rows then you can use :gt(int)
method:
$(function () {
$('#create').on('click', function () {
var table = $('#myTable')[0];
var rows = table.rows.length;
var row = '<tr><td>'+ rows +'</td><td>'+ rows +'</td></tr>';
$('#myTable').find('tr:eq(2)').after(row);
});
$('#delete').on('click', function () {
$('#myTable').find('tr:gt(2)').get(0).remove();
});
});
Using the above script you have to give your buttons specific ids #create
for row creation and #delete
for delete button like suggested below.
<button id='create'>Create row</button>
<button id='delete'>Delete row</button>
Note:
Unobtrusive javascript is better. Inline scripting should be avoided.
Updates:
Instead of hardCode in :eq(2) and :gt(2)
we can cache the length of the trs in table:
$(function () {
var o = $('#myTable').find('tr:last').index(); // cache it here
$('#create').on('click', function () {
var table = $('#myTable')[0];
var rows = table.rows.length;
var row = '<tr><td>' + rows + '</td><td>' + rows + '</td></tr>';
$('#myTable').find('tr:eq(' + o + ')').after(row); // place it here
});
$('#delete').on('click', function () {
$('#myTable').find('tr:gt(' + o + ')').get(0).remove(); // and here
});
});
$('#myTable').find('tr:last').index();
this line gets the last tr's index at the dom ready which is in this case 2
because .index()
is 0
based.