Antonio Ortiz Antonio Ortiz - 1 year ago 80
Javascript Question

How do I dynamically change the src attribute of a collection of images in JavaScript?

I have a document which has a specific path to images set:

<img src="img/"> // img in this case

What I'd like to do is change them all dynamically:

<img src="/new/path/">

This is my code:

var doc = document,
img = doc.getElementsByTagName('img'),
emailUrl = '/img/g',

for (var i = 0; i < img.length; i++) {
imgSrc = img[i].src;
imgSrc = imgSrc.replace(emailUrl, '/new/path/');

I stepped through the debugger and it doesn't seem to add them? What am I missing?

Answer Source

You need to reassign the replacement to the img.src. Regex is also not a string.

Also, it is important to note that when you are using relative paths, the browser may fill in the beginning portion of the URL. In the following example, you can see that the final result contains the full URL that the image was relative too. That will be important for you to remember as you set up your regular expressions.

var imgs = document.getElementsByTagName('img'),
  emailUrl = /\/img\//;

for (var i = 0; i < imgs.length; i++) {
  console.log('Before', imgs[i].src);
  imgs[i].src = imgs[i].src.replace(emailUrl, '/new/path/');
  console.log('After', imgs[i].src);
<img src="img/">
<img src="img/">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download