Search code examples
jquerypathimagesrcjquery-traversing

previous first img src - jQuery


i'm trying to obtain the src of an image placed before the link i click:

<ul id="grid">
        <li><a href="prod-det.php" class="tip" rel="product-tip.php"><img src="../upload/mainmenu-articolo-ico.jpg" width="110" height="115"><p>GSE29KGYCSS / GSE29KGYCWW</p></a>
        <div class="options">
            <a href="#briciole" class="opt-compare off">Compare</a>
            <a href="#briciole" class="opt-wish off">Wishlist</a>
        </div></li>

and write this path:

$('.options a').click(function() {
 $("#compare .myge-grid").append(closest('img').attr('src'));

but i fail to obtain the img src. Someone can please point me to the right direction? tks in advance

edit: more code here http://jsfiddle.net/X2NBn/1/


Solution

  • Update:
    According to your document structure, this is what you're looking for:

    $("img", $(this).parents('li:first')).attr("src");
    

    Note: attr("src") returns the src as defined in the HTML source ('../upload.png'). If you want the full path, use .prop("src") instead.


    Old answer
    You should define the JQuery object on which you want to use the .closest() method.

    Currently, you're not using the jQuery .closest method, but a (probably undefined) closest() function.

    This should work as intended, after adding $(this):

    $('.options a').click(function() {
        $("#compare .myge-grid").append($(this).closest('img').attr('src'));