<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 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');
alert(getvalue);
});
<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 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');
alert(getvalue);
});
Share
Improve this question
edited Oct 7, 2013 at 13:12
ljs.dev
4,4833 gold badges49 silver badges80 bronze badges
asked Jul 15, 2009 at 1:28
skargorskargor
1,0313 gold badges15 silver badges21 bronze badges
3 Answers
Reset to default 12Replace 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');
});
$('div.item').click(function() {
var getvalue = $(this).find('> p > img').attr('rel');
alert(getvalue);
});
You can't use 'this' like this.
Try:
$('div.item').click(function() {
var getvalue = $('p > img', this).attr('rel');
alert(getvalue);
});