Javascript – How to get the attr with jQuery


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

I have the above HTML code and I want to get the rel attribute's value when I click the image. I wrote this jQuery script, but it doesn't seem to work:

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

Best Answer

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');