Clarus Dignus Clarus Dignus - 7 months ago 118
Javascript Question

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/A@2x.png 2x">
</div>

Answer

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>