Getting the last row of a table using jQuery?

JavascriptJquery

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

2019

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

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

Last row id of table

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

Solution 8 - Javascript

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)". ";
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoshView Question on Stackoverflow
Solution 1 - JavascriptcoolguyView Answer on Stackoverflow
Solution 2 - JavascriptRamView Answer on Stackoverflow
Solution 3 - JavascriptcmartinView Answer on Stackoverflow
Solution 4 - JavascriptevilReikoView Answer on Stackoverflow
Solution 5 - JavascriptSharma VikramView Answer on Stackoverflow
Solution 6 - JavascriptPatrick MutwiriView Answer on Stackoverflow
Solution 7 - JavascriptIMRUPView Answer on Stackoverflow
Solution 8 - JavascriptAshif ShereefView Answer on Stackoverflow