23

Possible Duplicate:
Setting image src attribute not working in Chrome

When user clicks on "remove" link I need to set the src attribute of an image to empty. When I do it using

$('#img').prop('src', null);

src is not empty but points to current url

if I remove src using

$('#img').removeProp('src');

never let me to assign it back in the future

What's the best way to accomplish this?

Community
  • 1
  • 1
StackOverflower
  • 5,463
  • 13
  • 58
  • 89
  • 1
    Please see [this answer](http://stackoverflow.com/a/8425853/561731) – Naftali Dec 05 '12 at 15:35
  • An empty string can actually be a valid src for an image, technically speaking it is not "removing" the src. Same as `#`, it would use the current URL plus the hash. Real example: http://lcamtuf.coredump.cx/squirrel/ You would end up sending a request to the current URL. I would suggest using another approach. – Wesley Murch Dec 05 '12 at 15:42

3 Answers3

15

Try using attr(),

Live Demo

$('#img').attr('src', '');

As you have id selector. Using the native javascript method document.getElementById will give you more performance benefit. Also you may need to set # as src instead of empty string.

document.getElementById('img').src = "#";
Adil
  • 146,340
  • 25
  • 209
  • 204
6

I'd just access the underlaying <img> node and set the value of src to an empty string.

$('#img')[ 0 ].src = '#';

Fiddle: http://jsfiddle.net/P4pRu/


Update: It seems like Chrome is not satisfied when we just pass in an empty string. Firefox still shows the expected behavior (I'm pretty sure that this also worked in Chrome a couple of weeks/versions ago).

However, passing over a # for instance, works fine.


Update 2:

Even imgNode.removeAttribute('src'); does no longer remove the visual representation of an image anymore in Chrome (interesting...).

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • 1
    I'm afraid this doesn't work. Still pointing to current url instead of having an empty value. – StackOverflower Dec 05 '12 at 15:30
  • 1
    @TimmyO'Tool: indeed. Wierd behavior which to me seems, "new". However, it works if you pass in a `#` for instance. – jAndy Dec 05 '12 at 15:33
  • 2
    An empty string can actually be a valid src for an image, technically speaking it is not "removing" the src. Same as `#`, it would use the current URL plus the hash. Real example: http://lcamtuf.coredump.cx/squirrel/ You would end up sending a request to the current URL. – Wesley Murch Dec 05 '12 at 15:37
0

The attribute 'src' isn't really a property, it is an attribute. Think of properties as things that can be set with booleans or lists and attributes as things that are much more dynamic.

$('#img').attr('src', '');

As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes - http://api.jquery.com/prop/

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119