Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 573
tgriesser Avatar asked Feb 15 '26 21:02

tgriesser


1 Answers

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")
like image 113
GSerg Avatar answered Feb 18 '26 09:02

GSerg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!