Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's The Correct Way To Set Src Attribute In JQuery?

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!

like image 824
Shawn Avatar asked Dec 08 '10 17:12

Shawn


People also ask

How add src attribute in jQuery?

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.

Which function is used to set an attribute in jQuery?

Set Attributes - attr() The jQuery attr() method is also used to set/change attribute values.

What are jQuery attributes?

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.

How can add image in HTML using jQuery?

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.


2 Answers

When you do this:

$("#foo").attr("src", "bar2.jpg"); 

The previous src is replaced.

So you don't need:

$("#foo").removeAttr("src"); 

You can confirm it out here

like image 82
Sarfraz Avatar answered Sep 18 '22 17:09

Sarfraz


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/

like image 34
jon_darkstar Avatar answered Sep 20 '22 17:09

jon_darkstar