Search code examples
javascriptjqueryparent-childparent

Very basic question about parent() and prev() in jQuery


I am handling a hyperlink's click event with a JavaScript function. I want to retrieve data from the hyperlink.

The page looks like this:

<div class="div1">
   <div title="Title 1" class="div2">
      <p class="p1"><a class="linkJs">The link in question</a></p>
   </div>
</div>

<div class="div1">
   <div title="Title 2" class="div2">
      <p class="p1"><a class="linkJs">The link in question</a></p>
   </div>
</div>

And the JavaScript something like this:

$(function() {
   $('a.linkJs').click(function(){
      value=$(this).parent().prev().text();
      alert(value);
   });
});

What I want to have is the value of the TITLE in the div2. By clicking the first link I get : Title 1. And by clicking on the 2nd: Title 2.

This must be very very basic but I just can't find my answer anywhere.

Thanks.


Solution

  • You can find it with the closest method:

       $('a.linkJs').click(function(){
          value=$(this).closest('div').attr('title');
          alert(value);
       });