Derek
Derek

Reputation: 9943

Jquery Finding the closest link?

I want to be able to get the href from this type of code:

<tbody>
  <tr class="odd">
    <td class=" sorting_1">
      <a href="aURL">The Link Text</a>
    </td>
  </tr>
</tbody>

but I want to be able to click on the link itself, or the td.

Here is my CoffeeScript:

$("#myID tr td").click (event)->
    event.preventDefault()
    link = $(event.target).find("a").attr("href")
    $("#anAjaxPod").load(link)

This works if one clicks on the td, but not if if one clicks on the link.

Edit: Updated question, I used find at first. This is just the last code I played with

Upvotes: 2

Views: 8053

Answers (3)

PSL
PSL

Reputation: 123739

Use .find() ; .closest() is to climb up the DOM tree testing self and ancestors. Here anchor tag is the child of td so you need to descend down. So find or a children selector is what you need.

$(this).find("a").attr("href")

Closest get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

$("#myID tr td").click(function(event){
    event.preventDefault()
    link = $(this).find("a").attr("href");
    $("#anAjaxPod").load(link);
 });

Fiddle

Upvotes: 4

Binhvi
Binhvi

Reputation: 106

try this:

$(function(){
    $("#myID tr td").click(function(){
         Link = $(this).find("a").eq(0).attr("href");
         $("#anAjaxPod").load(Link);
         return false;
    })
})

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388376

.closest() looks and self or ancestors where as you want to descendent, to find the descendent use find()

link = $(event.target).find("a").attr("href")

Upvotes: 3

Related Questions