Reputation: 1473
In the following code, when the user clicks on the '.more'
span element, I want to retrieve information (eg, the ID) from the img
within the article
tag using jQuery.
Here's the HTML:
<article>
<img src="..." id="TR"/>
<div>some text <a>link</a> <span class="more">read more</span></div>
</article>
I've tried this code:
$('.more').click(function () {
var id = $(this).siblings().siblings('img').attr('id');
});
but it doesn't seem to work. Any thoughts?
Many thanks!
Upvotes: 1
Views: 3185
Reputation: 708026
You can do that like this:
$(".more").click(function() {
var id = $(this).closest("article").find("img:first").attr("id");
});
This looks up the parent tree for the containing <article>
tag. Then, it finds the first <img>
tag in that and gets its id value.
You can't use .siblings()
on $(this)
because the image isn't a direct sibling of $(this)
. You could use .siblings()
if you got the right parent that the img was a sibling of, but that's a little more fragile than what I've proposed. For example, this would also work, but it relies on more precise positioning of the HTML objects and any slight edits could break this code:
$(".more").click(function() {
var id = $(this).parent().prev().attr("id");
});
or
$(".more").click(function() {
var id = $(this).parent().siblings("img").attr("id");
});
You can't use .closest()
on the <img>
tag directly because the img isn't a parent of the .more
object.
If this were my code, I'd do it like this because it's the most flexible and the least likely to break if the HTML is edited slightly and you're sure to get the right img object, even if there are more images nearby:
<article>
<img class="target" src="..." id="TR"/>
<div>some text <a>link</a> <span class="more">read more</span></div>
</article>
$(".more").click(function() {
var id = $(this).closest("article").find(".target").attr("id");
});
Upvotes: 3
Reputation: 20431
You can use a regular class selector:
$('article > img[id]').attr('id');
Upvotes: 0
Reputation: 7449
Use parent().siblings() instead of siblings().siblings()
$('.more').click(function () {
var left = $(this).parent().siblings('img').attr('id');
alert(left);
});
See demo here
Upvotes: 2