Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
how to replace image srcset with javascript

I am doing an A/B Test. I need to change the image url. I have an https://newimage.svg that needs to replace the srcset img.png with javascript on the console:

<picture class="pic_test">
  <source media="(min-width: 992px)" srcset="img.png">
  <source media="(min-width: 600px)" srcset="img.png">
  <source media="(max-width: 599px)" srcset="img.png">
  <img src="img.png">
</picture>

This is an sample of the source structure. I can not put all the inside information because the confidencial job requirement but this is a summary (if adding this could help):

<source media="(min-width: 992px)" class="" src="" data-src="" data-srcset="img.png 960w,img.png 1176w,img.png 1600w,img.png 2400w" srcset="img.png 960w,img.png 1600w,img.png 2400w">

I have try so many things but it is not working. Does anyone knows how to change the image url with javascript or jquery?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If I understand your question correctly, you have a number <source> in a <picture> & you need to update all their srcset.

You can use querySelectorAll to select all the <source>, forEach to loop over them & finally use setAttribute to update the srcset attribute.

The source element also has a srcset property (MDN), but it is still experimental (as of Nov 2021).

var sourceList = document.querySelectorAll('picture.pic_test source');
sourceList.forEach((source)=> {
    source.setAttribute('srcset','img.png');
}); 
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use attr() function to change src attribute with jquery

console.log('before : '+$('#myImg').attr('src'));
$('#myImg').attr('src','google.png');
console.log('after : '+$('#myImg').attr('src'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<picture class="pic_test">
  <source media="(min-width: 992px)" srcset="img.png">
  <source media="(min-width: 600px)" srcset="img.png">
  <source media="(max-width: 599px)" srcset="img.png">
  <img src="img.png" id="myImg">
</picture>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda