Reputation: 93
i am replacing the img src attribute using javascript
my code is
<div class="reader" id="reader1"></div>
<img src="images/img_001.jpg" alt="image" id="image1"/>
</div>
and javascript code
$("#image1").attr("src").replace("images/img_001.jpg", "images/img_002.jpg");
the src attribute is not replacing
Upvotes: 2
Views: 898
Reputation: 41
You can directly set the value of src
with:
$("#image1").attr("src", "images/img_002.jpg");
Have a look at jQuery doc for attr()
.
Upvotes: 1
Reputation: 19262
or you can use prop()
$("#image1").prop("src", "images/img_002.jpg");
Upvotes: 0
Reputation: 136114
The reason is because the replace
method actually returns the new string - not edits it in place.
You can achieve what you want like this:
$("#image1").attr("src", function(){
return $(this).attr('src').replace("images/img_001.jpg", "images/img_002.jpg");
});
This sets a new value to the src
attribute by calling the function (second parameter). This function actiually returns
the replaced value.
Live example (check the src with developer tools): http://jsfiddle.net/4K3Dy/
Upvotes: 0
Reputation: 13843
You can change a value using
$('#image1').attr('src', 'images/img_002.jpg');
If you are using:
$('#image1').attr('src');
The function will return a string. String do NOT get passed by reference, but get copied instead. So modifying it doesn't actually change it.
Upvotes: 1
Reputation: 8275
See http://api.jquery.com/attr/#attr2 :
$("#image1").attr("src", "images/img_002.jpg");
Upvotes: 1
Reputation: 108500
You don’t need to call replace()
, just set the new src:
$("#image1").attr("src", "images/img_002.jpg");
Upvotes: 2