Reputation: 30915
i have simple html that looks like this :
<div class="img">
<a target="_blank" href="kl_big.htm" id="turn-of-cloth-01_lg">
<img src="images/galery/turn-of-cloth-01_lg.jpg" width="110" height="90" />
</a>
<div class="desc">Add a description of the image here</div>
</div>
i have like 20 sets of this div with different ids , now the href id im gtting with this
$(document).ready(function(){
$('a').click(function (event){
event.preventDefault();
var linkID =$(this).attr("id");
});
});
i dont know what is the img object id , but i need to get its src value . i tried with Jquery like this :
var imgSrcVal = $(this).siblings("img").attr("src");
but with out result , also tryied inside the click event but again with no results :
imgSrcVal = this.nextSibling.src;
what im doing wrong here ?
Upvotes: 0
Views: 11282
Reputation: 4024
I think this is what you want. The image is a child of the anchor tag, not a sibling.
$('a').click(function (event){
event.preventDefault();
var linkID =$(this).attr("id");
alert($(this).children('img').attr('src'))
});
Check out this fiddle
Upvotes: 3
Reputation: 1293
the img
tag in that example is not a sibling of the a
tag, it's a child. So to get the value of the src
attribute, you'd do $(this).children("img").attr("src")
Upvotes: 2
Reputation: 11327
The img
is nested, so use .find()
or .children()
.
var imgSrcVal = $(this).find("img").attr("src");
.find()
looks looks through all descendants
.children()
looks only at direct descendants
Or with native DOM methods:
var imgSrcVal = this.getElementsByTagName('img')[0].src;
The [0]
is because getElementsByTagName
returns an array-like collection. So [0]
gets the first element found.
Upvotes: 3
Reputation: 107566
The <img>
is not a sibling, it's a child of the anchor.
Try this instead:
$('a').click(function (event){
var linkID = $(this).attr("id");
var imgSrcVal = $('img', this).attr("src");
//alert(imgSrcVal);
return false;
})
Upvotes: 6