I'd like to use my image tag id="bla" src="....." in my web page by changing dynamically the src parameter. I usually do that with a selector and setting the src property, i.e.

$("#bla").prop("src", "/new/image/path.png")

but today I wanted to follow another way :

var bullet = $("#bla");  
bullet.src = "/new/image/path.png";

I expected that code change my picture in my HTML page, but it doesn't happen. The statement doesn't produce any error and if I watch my bullet.src value I find the new path for the new picture. If I query $("#bla").prop("src") I find the old path, could somebody tell me what's wrong?

3 Answers

Rajan On Best Solutions

If you do

var bullet = $("#bla");  

bullet will be an array of <img .. element. When you do change any attributes on that, it will not change.

You can do any of these, and change their property:

var bullet = $("#bla")[0];
// or
var bullet = $("#bla").get(0);

bullet.src = "/new/image/path.png";
carl On
Szekelygobe On

You need to use

bullet.attr('src', '/new/image/path.png');