JQuery change value <img src = "" by id

I need simple jQuery code, so I can change the src value for a specific img.

Currently:

<img id="myImage" src="image1.gif" /> 

and I need to change it to:

 <img id="myImage" src="image2.gif" /> 

using jquery.

+8
javascript jquery
source share
5 answers

Usage: $(function(){ ... });

You can use:

 $('#id').attr('src', 'newImage.jpg'); 

to immediately change the image source.


Alternatively, you can use jQuery animation to change the image.

Js

 $("#id1").fadeOut(); $("#id2").delay(200).fadeIn(); 

HTML

 <div> <img id='id1' src='one.jpg'> <img id='id2' src='two.jpg'> </div> 

(Remember to change CSS #id2 and put display: none as the initial state).

+11
source share

This is basic, use jQuery attr ...

 $('img#myImage').attr('src', 'image2.gif'); 
+12
source share

You can use the .attr() function to set attributes for a given DOM element:

 $(function() { $('#myImage').attr('src', 'image2.gif'); }); 
+6
source share
 $('#myImage').attr('src','theothersrc.gif') 
+6
source share
 $("#myImage").attr('src', 'image2.gif') 
+5
source share

All Articles