1

How can i get the data attribute of the last table row?

<tbody id="tableNotifications">
    <tr class="notificationsRowEntry success" data-notification-timestamp="1384105387"></tr>
    <tr class="notificationsRowEntry success" data-notification-timestamp="1384105367"></tr>
    <tr class="notificationsRowEntry success" data-notification-timestamp="1384105357"></tr>
    <tr class="notificationsRowEntry success" data-notification-timestamp="1384105323"></tr>
</tbody>

The problem is that i can't get the data attribute but only the content of the last table row using:

$data = $("#tableNotifications").last().data("notification-timestamp");

Maybe i'm doing a stupid mistake but it's driving me crazy.

Thank you.

P.S. I know that i could add some unique ids and then fetch the data with

 $data = $(uniqueid).data("notification-timestamp");

but i would like to avoid that.

siannone
  • 6,617
  • 15
  • 59
  • 89
  • 1
    Point of clarification: I think you're mistakenly thinking about how [`.last()`](http://api.jquery.com/last/) is used. It reduces the current set of matched elements (the ``) to the last one in the matched set (since you only select one element, this effectively does nothing in your case), as opposed to getting the immediate children (the ``s) of the element(s) in the matched set and getting just the last of those. You need to select the children elements in which you're interested in the first place, as in the below answers. – ajp15243 Nov 10 '13 at 19:55

3 Answers3

3

You want to get the value of the data attribute of the tr, not the tbody itself:

$("#tableNotifications > tr:last-child").data("notification-timestamp");
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
3

Use attr() function:

var data = $("#tableNotifications tr:last").attr("data-notification-timestamp");

The selector #tableNotifications tr:last selects the last tr child of the element with id tableNotifications.

Also this will work too:

var data = $("#tableNotifications tr").last().attr("data-notification-timestamp");

Just to clarify:

If you just want to get the attribute value from HTML use .attr("data-attr"). For more information see the difference between .data() and .attr().

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
3

That's finding the last element with the id of 'tableNotifications'. Simply append tr to your selector to get the last row:

$data = $("#tableNotifications tr").last().data("notification-timestamp");
Moob
  • 14,420
  • 1
  • 34
  • 47