Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  137] [ 4]  / answers: 1 / hits: 190613  / 13 Years ago, sun, september 18, 2011, 12:00:00

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


More From » jquery

 Answers
31

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);

[#90039] Friday, September 16, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;