Rosh
Rosh

Reputation: 1736

Getting the last row of a table using jQuery?

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

Answers (9)

evilReiko
evilReiko

Reputation: 20503

2019

As of jQuery 3.4.0 :last is deprecated, use .last() instead, like this:

var id = $('#mytable tr').last().attr('id');

Upvotes: 10

Camille
Camille

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

IMRUP
IMRUP

Reputation: 1513

Last row id of table

var lastid = $('table tr:last').attr('id');
var str = lastid .replace(/[^0-9]+/ig,"");

Upvotes: 0

Ashif Shereef
Ashif Shereef

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

Patrick Mutwiri
Patrick Mutwiri

Reputation: 1361

There are two methods and they both work $('#tableid tr:last') and $('#tableid tr').last()

Upvotes: 1

cmartin
cmartin

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

Sharma Vikram
Sharma Vikram

Reputation: 2480

var tid=$('#tableid tr:last').attr('id');
alert(tid);

Upvotes: 2

Ram
Ram

Reputation: 144739

var id = $('table tr:last').attr('id');

Upvotes: 15

coolguy
coolguy

Reputation: 7954

$('#yourtableid tr:last').attr('id');

Upvotes: 136

Related Questions