image – Access img tag src using jQuery – Education Career Blog

Can I do this?

$("#myImage"+1).attr("src", "path/to/newImage.jpg");

Because the image is like an array so the id for the img tag is myImage1

<img src="path/to/oldImage.jpg" id="myImage1">


Yes, you could iterate round image elements like this:

for (var i=0;i<=5;i++)
 $("myImage" + i).attr("src", "path/to/newImage.jpg"); ?


Yes. You can do that.

jQuery selectors are just strings. How you put together the string is really of no concern to jQuery. It doesn’t know, it doesn’t care, it’ll never ask questions. As long as your completed string is a valid selector (which it is once you’ve concatenated it as in your example), jQuery will know what to do.


Yes that’s valid code for jQuery 🙂 It is same as you do the concatenation with Javascript.


Yes you can.
Isn’t it easier to try it before posting? it would take less time…


You can subscript jQuery objects like an array


or the more verbose jQuery get(0).

However, if you were just string building a jQuery selector, then yes, of course that will work. jQuery doesn’t know how that string was made (or does it care), so long as it is a valid selector.

Leave a Comment