How to change picture element srcset value with jQuery

8.4k views Asked by At

How does one target the srcset property of the source tag within a picture element with jQuery? What is the correct jQuery code to change the value of xxxxxxxxxx.jpg and yyyyyyyyyy.jpg below?

<picture>
    <!--[if IE 9]><video style="display: none;"><![endif]-->
    <source media="(min-width: 992px)" srcset="/images/bannerAds/xxxxxxxxxx.jpg">
    <source media="(min-width: 768px)" srcset="/images/bannerAds/yyyyyyyyyy.jpg">
    <source srcset="/images/bannerAds/zzzz_320x50.png">
    <!--[if IE 9]></video><![endif]-->
    <img src="data:image/gif;base64,R0lGODlhAQABAAAAADs=" alt="Clio">
</picture>
2

There are 2 answers

1
syanaputra On

Well there are many ways to get it done. And honestly, someone's correct approach may not be the correct one for you due to various reasons.

This is an approach.

function replace_srcset(target, replacement)
{
    // Search for the target
    $('source[srcset="'+target+'"]').attr('srcset', replacement);
}

replace_srcset('/images/bannerAds/xxxxxxxxxx.jpg', '/images/bannerAds/somethingelse.jpg');
0
fregante On

If you want to change the src then you want to overwrite all the sources. Just remove them since you're not using them:

$('picture source').remove();

And then set the src normally:

$('img').attr('src', 'your-new-image.jpg');

If you want to use multiple src by keeping it responsive, then use Stephanus' code multiple times.