vsm vsm - 4 months ago 36
Javascript Question

How to fetch img srcset url using jquery

I have an image tag with srcset attribute holding a value(url). Now i need to fetch and generate same for src attribute as well.

$('img').attr('srcset')


The above code is not working and returns undefined.

<img srcset="http://s7d2.scene7.com/is/image/Hod/Mobile600x160?$600x160$" alt="">


I need to fetch above srcset value("http://s7d2.scene7.com/is/image/Hod/Mobile600x160?$600x160$") and append the same value for src attribute. Kindly help.

Thanks in advance.

Answer

you need to wait till the dom is loaded: $(document).ready(function(){})

$(document).ready(function(){
  var img = $('.img');
  img.each(function(){
    this.src = this.srcset;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img class="img" srcset="http://s7d2.scene7.com/is/image/Hod/Mobile600x160?$600x160$" alt="">
<img class="img" srcset="http://s7d2.scene7.com/is/image/Hod/Mobile600x160?$600x160$" alt="">

you still can change back to $('img') instead of $('.img') but be aware that then every img tag will be progressed.