JQuery DOM Traversal

I'm having trouble finding the easiest way to an element using jQuery (although it’s not necessary to use jQuery for the solution, it is just available as a tool). Here is an example of simplified code:

<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 want to get the word “Workshop” when the “Delete” link is clicked, and I wonder what is the most effective way to do this. It would be: a) go one level up the tree to the element <td>and find the sibling element by class name, then the link / text value inside ... b) go to the level <tr>and search for the class name, etc. or c) to do what I did not consider.

It always seems to me that I am having problems understanding when and how to do JavaScript crawls in javascript or jquery, and you want to know why there are different methods available and whether it matters how you achieve the final result.

+3
source share
3 answers

This simple scheme is often better:

  • Say in plain language what you want to find.
  • Treat the result as pseudocode.
  • Literally translate it into code.

In your case, this is possible:

I need <td class = "class-name"> on the row to which the clicked element belongs.

This translates directly to your parameter b):

$(this).closest("tr").find("td.class-name")
+3
source
+1
source
$("td.class-name a", $(this).closest("tr")).text())

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

Demo

0
source

All Articles