Suppose I have the following HTML:
<img id="foo" src="bar1.jpg"/>
I would like to switch the src
to bar2.jpg
Can I just do this?
$("#foo").attr("src", "bar2.jpg");
Or do I have to do this?
$("#foo").removeAttr("src"); $("#foo").attr("src", "bar2.jpg");
Thanks!
Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.
Set Attributes - attr() The jQuery attr() method is also used to set/change attribute values.
jQuery attribute methods allows you to manipulate attributes and properties of elements. Use the selector to get the reference of an element(s) and then call jQuery attribute methods to edit it. Important DOM manipulation methods: attr(), prop(), html(), text(), val() etc.
With jQuery, you can dynamically create a new image element and append it at the end of the DOM container using the . append() method. This is demonstrated below: jQuery.
When you do this:
$("#foo").attr("src", "bar2.jpg");
The previous src
is replaced.
So you don't need:
$("#foo").removeAttr("src");
The first wey is just fine, no reason to remove it first.
$("#foo").attr("src", "bar2.jpg");
$.attr serves both to get the existing attribute and to change it (depending on whether theres one or two arguments). Your situation is exactly what he second functionality is intended for, and the attribute 'src' is not special.
http://api.jquery.com/attr/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With