2

I have two images, one transparent:

http://www.example.com/image-trans.png

And another one with a background:

http://www.example.com/image.png

I am trying to use jQuery to change the src of the image from image-trans.png (original value) to image.png when a certain event is triggered.

I am able to accomplish this by typing the src directly into my jQuery code:

$("img.nav51").attr("src","http://example.com/image.png");

However, I am trying to do this without typing the URL directly into my jQuery, as the URL is dynamically set elsewhere, and is subject to change.

Here is what I am trying, but it does not do anything for me:

$('img.nav51').attr("src").replace("-trans.png", ".png");

Any suggestions?

1
  • Replace doesn't modify the string you are "replacing." Rather it returns a new string which you must then set as the new src attribute. Commented Jul 30, 2014 at 14:51

3 Answers 3

4

To set/update the attribute you must pass the new value in the second parameter.

Try this :

var originalSrc = $('img.nav51').attr("src");
$('img.nav51').attr("src", originalSrc.replace("-trans.png", ".png"));
Sign up to request clarification or add additional context in comments.

2 Comments

Or he could just use this.src = this.src.replace("-trans.png", ".png"); I'm all for all jQuery, but sometimes, the simplest solution is Vanilla. That is, if this is in a click event of the image
Depending of his needs, yes.
1

You have to set it to replace it:

$('img.nav51').attr("src", $('img.nav51').attr("src").replace("-trans.png", ".png"));

Comments

0
$('img.nav51').attr('src', function(){ 
     return this.src.replace("-trans.png", ".png"); 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.