Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  112] [ 4]  / answers: 1 / hits: 16868  / 9 Years ago, sun, april 26, 2015, 12:00:00

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


More From » jquery

 Answers
6

'.child:last' selector will select the last element having child class. As child class is applied to <table>, this selector will select table element, while you want to select last <tr>.



As there is no data attribute on <table>, .attr('data') on it will return undefined.



To get the value of data attribute on last <tr> use the selector tr:last.



var value = $(this)           // Button that is clicked
.parent() // Direct parent element i.e. div.parent
.find('.child tr:last') // Get the last <tr> inside .child
.attr('data'); // Get value of data attribute


As the .child element is next to the button, next() can be used to get the table.child element.



var value = $(this)           // Button that is clicked
.next('.child') // Next element i.e. table
.find('tr:last') // Get last <tr>
.attr('data'); // Get value of data attribute





I'll recommend to use data-* attribute to store data in custom attribute.



<tr data-num=0>Foo</tr>
<tr data-num=1>Bar</tr>


And to get the value of custom data attribute use data()



.data('num')





If you just want to get the index of the last tr, there is no need to store that on element. You can get the index by using the index().



.index()


This will return index of an element. Note that this is zero-based index which is exactly how you want.


[#66891] Friday, April 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
morganm

Total Points: 626
Total Questions: 95
Total Answers: 95

Location: South Sudan
Member since Sun, Jul 11, 2021
3 Years ago
;