manuelgu manuelgu - 1 month ago 10
CSS Question

Access elements inside a div outside of the current div

This is probably a very easy approach, however I haven't been able to figure it out.

My approach is to get all

<img>
elements that have the "expanded-image" class that are within the "img-preview" of my current "entry".

This is my html:

<div class="entry">
<div class="img-preview">
<img>
<img class="expanded-image" style="display:none;">
</div>

<div class="content">
[..]
[..]
<span class="more-text"></span>
[..]
[..]
</div>
</div>


And this is the JS I work with:

$('.content').each(function(event) {

$(this).find('span.more-text').click(function(event) {

// TODO

});
});

Answer

Firstly you don't need the each() at all as you can apply the click() event handler to all elements within a single selector.

To solve your issue you can use closest() to find the nearest parent .entry element to the clicked .more-text. From there you can find() all the .expanded-image elements. Try this:

$('.content span.more-text').click(function(event) {
    var $imgs = $(this).closest('.entry').find('.img-preview .expanded-image');
    // work with $imgs here...
});
Comments