Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set image src to empty? [duplicate]

Tags:

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?

like image 443
StackOverflower Avatar asked Dec 05 '12 15:12

StackOverflower


People also ask

How to set image src to empty?

To clear an image src attribute: Use the setAttribute() method to set the image's src attribute to an empty string.

Can img src be empty?

Use the getAttribute() method to check if an image src is empty, e.g. img. getAttribute('src') . If the src attribute does not exist, the method returns either null or empty string, depending on the browser's implementation.

How img src works?

The src attribute contains a path pointing to the image you want to embed in the page, which can be a relative or absolute URL, in the same way as href attribute values in <a> elements. Note: You should read A quick primer on URLs and paths to refresh your memory on relative and absolute URLs before continuing.

What is image src?

HTML | <img> src Attribute The <img> src attribute is used to specify the URL of the source image. Syntax: <img src="URL"> Attribute Values: It contains single value URL which specifies the link of source image. There are two types of URL link which are listed below: Absolute URL: It points to another webpage.


2 Answers

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 = "#"; 
like image 146
Adil Avatar answered Sep 21 '22 06:09

Adil


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...).

like image 23
jAndy Avatar answered Sep 21 '22 06:09

jAndy