Reputation: 1736
I'm dynamically creating table rows. So each time I add a row, I need to get the ID of the last <tr>
so that I can create a new <tr>
with ID = "(the last row's ID) + 1"
. Is there any way to get the last row's ID using jQuery?
Upvotes: 65
Views: 121807
Reputation: 20503
As of jQuery 3.4.0 :last
is deprecated, use .last()
instead, like this:
var id = $('#mytable tr').last().attr('id');
Upvotes: 10
Reputation: 879
I was looking for a Vanilla javascript solution and this question is the first Google result, so here is the solution without Jquery :
let table = document.getElementById('myTable') ;
let lastLine = table.rows[table.rows.length-1];
Upvotes: 0
Reputation: 1513
Last row id of table
var lastid = $('table tr:last').attr('id');
var str = lastid .replace(/[^0-9]+/ig,"");
Upvotes: 0
Reputation: 494
You don't need to use jQuery for that. You can handle it in CSS counters. The counters automatically increments the index values and it also handles the rearrangement of numbers in case a row is deleted from the midst. The CSS counters can be implemented as follows. Insert it into your CSS file that take care of the styles of the HTML table.
#yourtableid tbody
{
counter-reset: tablerow;
}
#yourtableid tbody .yourHTMLcellclass::before
{
counter-increment: tablerow;
content: counter(tablerow)". ";
}
Upvotes: 0
Reputation: 1361
There are two methods and they both work $('#tableid tr:last')
and $('#tableid tr').last()
Upvotes: 1
Reputation: 2941
Old question, but here's a different way using JQuery traversal which is a bit quicker:
$("#TableId").find("tr").last();
An alternative method to ID your rows, if they are all sequential is just to get the number of rows + 1.
$("#TableId").find("tr").length + 1
Upvotes: 17