jQuerybeast
jQuerybeast

Reputation: 14490

Dynamically replace img src attribute with jQuery

I am trying to replace the img source of a given source using jQuery. For example, when the image src is smith.gif, replace to johnson.gif. If williams.gif replace to brown.gif etc.

EDIT: The images are retrieved from an XML to a random order, without class to each .

This is what I tried:

if ( $("img").attr('src', 'http://example.com/smith.gif') ) {
              $(this).attr('src', 'http://example.com/johnson.gif');
            }
if ( $("img").attr('src', 'http://example.com/williams.gif') ) {
              $(this).attr('src', 'http://example.com/brown.gif');
            }

Note that my HTML has many images. For example

<img src="http://example.com/smith.gif">
<img src="http://example.com/williams.gif">
<img src="http://example.com/chris.gif">

etc.

So, how can I replace the images: IF img src="http://example.com/smith.gif" then show "http://example.com/williams.gif". etc...

Thanks alot

Upvotes: 35

Views: 196815

Answers (3)

Primoshenko
Primoshenko

Reputation: 140

In my case, I replaced the src taq using:

   $('#gmap_canvas').attr('src', newSrc);

Upvotes: 5

uadnal
uadnal

Reputation: 11435

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

Upvotes: 21

Niko
Niko

Reputation: 26730

This is what you wanna do:

var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);

Upvotes: 82

Related Questions