Search code examples
jqueryresponsive-designretina

Output img.currentSrc of srcset using jQuery


I need to output the current source of an image using a jQuery alert:

alert($('.someclass img').attr('currentSrc'));

...however the alert is outputting undefined.

For reference, the mark-up is as follows:

<div class="someclass">
    <img srcset="http://example.com/A.png, http://example.com/[email protected] 2x">
</div>

Solution

  • currentSrc is a property not an attribute. Use .prop('currentSrc')

    $(function() {
    
      console.log($("img").prop("currentSrc"));
      
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="someclass">
        <img srcset="https://webkit.org/demos/srcset/image-1x.png, https://webkit.org/demos/srcset/image-2x.png">
    </div>