简体   繁体   中英

Select siblings of siblings in jQuery

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!

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");
});

Use parent().siblings() instead of siblings().siblings()

$('.more').click(function () { 
    var left = $(this).parent().siblings('img').attr('id');
    alert(left);
});

See demo here

您可以使用常规的类选择器:

$('article > img[id]').attr('id');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM