views:

57

answers:

5

Hi,

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.

+2  A: 

You can find it with the closest method:

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

You want to use closest

var value = $(this).closest('div').attr('title');

Your problem is that the <p> tag is not a sibling to the <div> but a child, so you would have to do parent() twice - there's no need, though, as the closest function is a handy shortcut. Also, the text() function returns the pure text contents inside the tag, if you want the title attribute of the tag you need to use the attr function.

Paolo Bergantino
+1  A: 

try using the closest() method: http://api.jquery.com/closest/

Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

$(function() {
    $('a.linkJs').click(function(){
        value=$(this).closest(".div2").attr("title");
        alert(value);
    });
});
hunter
A: 
var value = $(this).closest('.div2').attr('title');

Instead of using div, .div2 may be a more appropriate selector because there may be other div elements inside div.div2.

Zafer
A: 

Not very pretty, but this should work too.

$(function() {
    $('a.linkJs').click(function(){
        value=$(this).parents()[1];
        alert($(value).attr('title'));
    });
});
Rocket