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

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


Just do .attr('src', 'foo') because you're assigning a src regardless. Only remove the attribute if you don't need it entirely.


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/