Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last element in the .find() object by jquery

I have DOM like this:

<div class="parent">
   <button class="add-tr">Add</button>
   <table class="child">
   <tr data="0"></tr>
   <tr data="1"></tr>
   ...
   </table>
</div>
<div class="parent">
   <button class="add-tr">Add</button>
   <table class="child">
   <tr data="0"></tr>
   <tr data="1"></tr>
   ...
   </table>
</div>
...

When I click on the Add button, I would like to get the value of the data attribute from the last of it own parent class.

I am using this method to get the last element,but it doesn't work.

$('.add-tr').click( function() {
   var last = $(this).parent().find('.child:last').attr('data');
   alert(last);
})

Any idea why? Or any other suggestion to get the last element in the table?

UPDATE Yes, I found the problem, turn out is I forgot the 'tr'. Thanks for your guys answer. All your guys giving the correct answer, I wish I can accept all your answers. Thanks

like image 409
dev-jim Avatar asked Feb 10 '23 08:02

dev-jim


1 Answers

Try this

   var last = $(this).parent().find('.child').find('tr').last().attr('data');

In your example you get last table, but you need get last tr

Example

like image 63
Oleksandr T. Avatar answered Feb 12 '23 20:02

Oleksandr T.