MS.
MS.

Reputation: 43

Changing individual image sources with jQuery

I need to change the image sources of multiple individual images on a site containing many. They do not have IDs I could use to identify each individual image, which is why I need to make the changes based on the current source each image has.

I have not managed to find a working solution to this.

The html looks like this:

<img class="card-image" alt="" src="www.url.com/12987237857.an-individual-photo.jpg">

Ive found and tried many variations of this but have not found a way to make this change only a specific img src:

  $('.card-image').attr('src', $('.card-image').attr('src').replace('original', 'new'));

I have done something similar before with hrefs and this worked perfectly:

 $('a[href$="partOfOldURL"]').attr('href', 'newURL');

Could someone help me out? Thank you in advance!

Upvotes: 2

Views: 37

Answers (3)

Karan
Karan

Reputation: 12619

You can use attribute selector [] as with proper condition.

As your tag is img and want to update src use $('img[src$="partOfOldURL"]'). And .attr('src', 'newURL');

Use ^ to match element with href start with partOfOldURL

$('img[src^="partOfOldURL"]').attr('src', 'newURL');

Use $ to match element with href end with partOfOldURL

$('img[src$="partOfOldURL"]').attr('src', 'newURL');

Use * to match element with href contains partOfOldURL

$('img[src*="partOfOldURL"]').attr('src', 'newURL');

Please review jQuery selectors to learn more.

Upvotes: 0

palaѕн
palaѕн

Reputation: 73906

You can easily do this using .attr( attributeName, function ) like:

$(".card-image").attr("src", function(i, val) {
  return val.replace('individual', 'new');
});

Demo:

$(".card-image").attr("src", function(i, val) {
  return val.replace('individual', 'new');
});

$(".card-image").each(function() {
  console.log($(this).attr("src"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="card-image" alt="" src="www.url.com/12987237857.an-individual-photo.jpg">
<img class="card-image" alt="" src="www.url.com/12985555555.an-individual-photo.jpg">

You can see in this demo individual text in the src is replaced with new and the updated src is also shown in the console. You can replace any text you want inside the function.

Upvotes: 1

miile7
miile7

Reputation: 2393

I suggest using the jQuery.each function.

$(document).ready(function(){
  $('.card-image').each(function(){
    $(this).attr('src', $(this).attr('src').replace('original', 'new'));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="card-image" alt="" src="https://via.placeholder.com/150?text=original+1234">
<img class="card-image" alt="" src="https://via.placeholder.com/150?text=original+5678">

Upvotes: 1

Related Questions