Home > Back-end >  How do I replace only part of an image source?
How do I replace only part of an image source?

Time:02-18

Is there a way to use jQuery to change a part of an image's source URL?

I'm working on a page that has a number of image elements that are all programmatically generated (but I'm not able to access the source code that generates them). And they all share the same class.

Let's say I have the following HTML:

<img src="https://cdn.example.com/pictures/01.jpg" >
<img src="https://cdn.example.com/pictures/02.jpg" >
<img src="https://cdn.example.com/pictures/03.jpg" >
<img src="https://cdn.example.com/pictures/04.jpg" >

Simple enough. But now, what if I want to point them all to a different directory? Like: /images/

So far, I've tried a few things, including this bit of jQuery, but nothing's done the trick so far:

$("img.photo").attr("src").replace("pictures","images");

That feels like it should do it because it's targeting images with that class -> then the "src" attribute -> and telling it to replace "pictures" with "images."

But I'm extremely new to using jQuery, so I'd appreciate some help.

What am I missing here? Any advice?

UPDATE: Huge thanks to those who provided answers and explanations — I really appreciate you helping a beginner!

CodePudding user response:

In your code you simply change the returned string from $("img.photo").attr("src") without doing anything with it afterwards. This will not change the attribute in your <img> elements.

This should do the job:

$("img.photo").each(function(){this.src=this.src.replace("pictures","images")})

Here I go through all the matched elements and assign the changed src string back to each element's srcattribute.

$("img.photo").each(function(){this.src=this.src.replace("pictures","images")});

// list the changed src values in the console:
console.log($("img.photo").map((i,img)=>img.src).get())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://cdn.example.com/pictures/01.jpg" >
<img src="https://cdn.example.com/pictures/02.jpg" >
<img src="https://cdn.example.com/pictures/03.jpg" >
<img src="https://cdn.example.com/pictures/04.jpg" >

CodePudding user response:

Your code snippet won't work, because that's grabbing the src attribute of the first image, and changing it, but never setting the result as the new src on the <img> elements.

Try this

  $("img.photo").each((index, img) => {
    img.src = img.src.replace("pictures","images");
  });
  • Related