views:

1279

answers:

3
<div class="item">
  <p><img src="images/photos_sample1.jpg" 
          border="0" rel="images/google_map.jpg"></p>
  <p>Dining Area</p>
</div>
<div class="item">
  <p><img src="images/photos_sample2.jpg" 
          border="0" rel="images/sample_photo.jpg"></p>
  <p>Pool Area</p>
</div>

I have this html code, and I want to get the rel attribute's value when I click the image.I wrote this jquery script, but seems not work

$('div.item').click(function() {
  var getvalue = $('this > p > img').attr('rel');
  alert(getvalue);
});
+2  A: 

Replace this:

var getvalue = $('this > p > img').attr('rel');

With this:

var getvalue = $(this).find('p > img').attr('rel');

As it is right now you are doing a global search for elements with the literal tag name this

An equivalent code would also be:

var getvalue = $('p > img', this).attr('rel');

Although by the looks of it the items are image/caption combinations and you wouldn't really expect other images, in which case it is better to just do:

var getvalue = $(this).find('img').attr('rel');

Or maybe give it a descriptive class and replace img with img.someclassname - this would make it so that if you edit your HTML later on your Javascript doesn't break because of your specific selector.

Furthermore, you could just bind the click event to the images themselves:

$('div.item img').click(function() {
    var getvalue = $(this).attr('rel');
});
Paolo Bergantino
A: 
$('div.item').click(function() {
        var getvalue = $(this).find('> p > img').attr('rel');
        alert(getvalue);
        });
alex
A: 

You can't use 'this' like this.

Try:

$('div.item').click(function() {
        var getvalue = $('p > img', this).attr('rel');
        alert(getvalue);
        });
SolutionYogi