Stanley
Stanley

Reputation: 569

jQuery child selector help

There must be a better way to select this element. Can someone please help me out. I've tried nth-child and last-child, but I'm not getting it.

Here's my code:

<li>
    <div class="pic" style="width:300px; text-align:center;">
        <img src='path/to/my/image.jpg' />
    </div>
    <p>
        <span title="<?php echo $media_title; ?>">Title: <?php echo stringDisplay($media_title,12); ?></span><br />
        <span title="<?php echo $media_filename; ?>">File: <?php echo stringDisplay($media_filename,18); ?></span><br />
        Updated: <?php echo date("n/j/y", $lastUpdated).' at '.date("h:ia",$lastUpdated); ?>
    </p>
    <a class="link" href="javascript:;" onclick="alert($(this).parent().children('.pic').children().children().children().attr('src'));" style="margin-bottom:3px;">Preview</a>
</li>

I'm trying to select the image source of the image in the first div from the link below it. The best I could come up with is:

alert($(this).parent().children('.pic').children().children().children().attr('src'));

Upvotes: 0

Views: 203

Answers (3)

Mark Schultheiss
Mark Schultheiss

Reputation: 34227

Find the first sibling with an image element and return the src attribute.

$(this).prevAll().find('img:first').attr('src');

Upvotes: 1

user113716
user113716

Reputation: 322622

This is how I would do it:

$(this).siblings('.pic').children('img').attr('src');

There are many ways to traverse in jQuery:

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 360056

Is this what you're looking for?

$(this).parent().find('div.pic>img').attr('src');

N.B. I would strongly recommend not using onclick to bind your Javascript event handlers.

Upvotes: 1

Related Questions