JQuery: I have a class, I repeat it with each one. The result is different every move. How do I use this and access the value?
I am starting and this is the first time we face such a problem.
I am iterating over the class using every method provided by jQuery. There are many classes with the same name on the page. Therefore, we can expect it to be 15 iterations.
Each iteration has a different meaning.
$(".book").each(function(n) {
var result = $(this
I need to get the latest TD with a list of values. So my option is to use
$(".book tbody tr:last")
But I think this thing won't work in every environment because it won't know what context it is handling.
$ (this tbody tr: last one) won't work either. How can I create a selector that will work?
<div class = "book">
<p class = "chapter">
<table>
<tbody>
<tr>
<td>General</td>
<td>
<b>Buck</b>
</td>
</tr>
<tr>
<td>General</td>
<td>List</td>
</tr>
</tbody>
</table>
</p>
</div>
a source to share
Assuming you posted HTML, there is a separate book and there are many others like it, and you want to access the latest <tr>
in each one, this should work:
$('div.book tbody tr:last-child').each(function() {
var value = $(this).find('td').eq(1).text();
});
value
will then be a "list" with the HTML above, and if you have multiple <div>
, it will iterate, as you might expect, through the last of <tr>
each.
The key here is what we use last-child
instead of . The documentation says it will match the last selected item; we don't want that. Instead, we want to specify : Matches all elements that are the last child of their parent. This distinction is important in this particular case, since we only want the last child of the table we are currently in, we don't want the last result as a whole. last
last
last-child
If you wanted to get the latest <td>
for the latest <tr>
, we could even do this:
$('div.book tbody tr:last-child td:last-child').each(function() {
var value = $(this).text();
});
This selector will select every last child <tr>
and select its matching last-child <td>
. It would be better if you don't care what the meaning of the former is <td>
. If you do, you want to use the first one.
a source to share
If you're only iterating over items tr:last
, Paolo's answer should work for you. However, if you need to run multiple queries for each div.book
, try this instead:
$("div.book").each(function() {
$("tbody tr:last", this).doStuff();
$("p.chapter", this).doOtherStuff();
}
The second argument to the dollar function is the "context node" and the default is document
(ie, it "searches" for the entire DOM).
a source to share