Search code examples
jquery

How can I get image with custom attribute using jQuery?


Can you please give me a hint on how do I get the value of a specific image by a custom attribute . For example, I have :

<img class="image" 
     identif="<?php echo $j; ?>" 
     id="<?php echo $id; ?>" 
     src="../<?php echo $sqlg[$pic] ?>" 
     h="<?php echo $heightl; ?>" 
     w="<?php echo $widthl ?>"
     height="<?php echo $height; ?>px" 
     width="<?php echo $width; ?>px" 
     title="Double-click to enlarge image" />

I want in jquery to get the "src" of the image by the "identif" attribute, thank you :)


Solution

  • It's better to use instead a data-* attribute like so

    <img class="image" data-identif="<?php echo $j; ?>"...
    

    and thus you can retrieve that attribute with

    $('img[data-identif]').data('identif');
    

    See http://api.jquery.com/jQuery.data/ for further reference

    If you need to grab the src of an img with data-identif = 5 just do like so:

    $('img[data-identif="5"]').attr('src');