views:

60

answers:

3

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'));
+1  A: 

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.

Matt Ball
+1  A: 

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

$(this).prevAll().find('img:first').attr('src');
Mark Schultheiss
wow! that was fast! thank you geniuses - I just can't seem to wrap my head around jquery selectors. thanx!
Stanley
You are welcome. Feel free to post more questions. It is recommended that you click the green arrow next to the answer that helped you once you have verified it - that will keep the StackOverflow crowd helping you out as some get grumpy if you do not accept answers (not me though)
Mark Schultheiss
+1  A: 

This is how I would do it:

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

There are many ways to traverse in jQuery:

patrick dw