tgriesser
tgriesser

Reputation: 2808

jQuery DOM Traversal

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

Answers (3)

GSerg
GSerg

Reputation: 78155

This simple schema is often the best:

  1. Say in plain English what you want to find.
  2. Treat the result as pseudo-code.
  3. Literally translate it to code.

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

amit_g
amit_g

Reputation: 31250

$("td.class-name a", $(this).closest("tr")).text())

$(this).closest("tr").children(":nth-child(2)").children("a").text()

Demo

Upvotes: 0

Alxandr
Alxandr

Reputation: 12423

This works: http://jsfiddle.net/JCz6L/

Upvotes: 1

Related Questions