David Jones
David Jones

Reputation: 10219

Combining parent() and children() selectors in JQuery

I currently have the following series of JQuery selectors:

$(this).parent().parent().children('a').children('img').attr('src')

It works just fine but is there a more compact way to do this?

UPDATE

Here's my HTML structure:

<div class="preview">
    <a><img src="#"></a>
    <div class="info">
        <div class="item">This is where we start.</div>
    <div>
</div>

Upvotes: 0

Views: 1585

Answers (3)

SpYk3HH
SpYk3HH

Reputation: 22570

With that HTML, one way would be:

$(this).parents(".preview").find("a img").attr("src");

You could also easily:

$(this).parent().prev().children("img").attr("src");

Although, if you can make use of HTML5, my suggestion would be to add a data-ref to the start element div as follows:

<div class="item" data-ref="#imgID-1">This is where we start.</div>
// and of course add an id to the img
<img id="imgID-1" src="blah.png" />

Then you can easily recall as:

var source = $($(this).data("ref")).attr("src");

Upvotes: 0

easement
easement

Reputation: 6139

You could do something like:

$(this).closest('.preview').find('a img').attr('src')

Closest Docs | Find Docs

Upvotes: 2

Faust
Faust

Reputation: 15404

This would work given your initial condition, regardless of the specific markup:'

$(this).parent().siblings('a').children('img').attr('src')

Upvotes: 3

Related Questions