Reputation: 2808
I'm having trouble finding the easiest path to an item using jQuery (although the solution doesn't have to necessarily use jQuery, it's just available as a tool). Here is a simplified code sample:
<tr>
<td>Bob Jones</td>
<td class="class-name">
<a href="/start/1">Workshop</a>
</td>
<td>06/04/11</td>
<td class="last">
<a href="#" class="button">Delete</a>
</td>
</tr>
I'm looking to get the word "Workshop" when the "Delete" link is clicked, and I'm wondering which is the most efficient means of doing so. Would it be to a) go one level up the tree to the <td>
element and find the sibling element by class name, then the link/text value inside... b) to go up to the <tr>
level and search for the class-name, etc. or c) do something I hadn't considered.
I always seem to have trouble with understanding when and how to do dom traversal in javascript or jquery and wanted to know the why's behind different methods available, and whether it matters how you get to the end result.
Upvotes: 3
Views: 444
Reputation: 78155
This simple schema is often the best:
In your case, it's probably:
I need <td class="class-name"> on the row to which the clicked element belongs.
This translates directly to your b)
option:
$(this).closest("tr").find("td.class-name")
Upvotes: 3
Reputation: 31250
$("td.class-name a", $(this).closest("tr")).text())
$(this).closest("tr").children(":nth-child(2)").children("a").text()
Upvotes: 0