Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear an IMG with jQuery

Tags:

html

jquery

image

I'm trying to remove the loaded image from a <img> element, but clearing or removing the src doesn't do it. What to do?

HTML:

<img src='https://www.google.com/images/srpr/logo3w.png'>

JQUERY:

$('img').attr('src', ''); // Clear the src
$('img').removeAttr('src');​ // Remove the src

Image remains...

fiddle: http://jsfiddle.net/6x9NZ/

like image 966
Yarin Avatar asked Jun 02 '12 20:06

Yarin


People also ask

How to remove an image using jQuery?

jQuery remove() Method This method also removes data and events of the selected elements. Tip: To remove the elements without removing data and events, use the detach() method instead. Tip: To remove only the content from the selected elements, use the empty() method.


4 Answers

You would have to either remove the <img> element entirely or replace it with a different image (which could be a transparent gif).

like image 137
Quentin Avatar answered Oct 14 '22 10:10

Quentin


This worked for me:

var $image = $('.my-image-selector');
$image.removeAttr('src').replaceWith($image.clone());

However, be wary of any event handlers that you might have attached to the image. There's always the withDataAndEvents and deepWithDataAndEvents options for jQuery clone, but I haven't tested the code with them: http://api.jquery.com/clone/#clone-withDataAndEvents

Also, if you want to do this for multiple images, you will probably have to use something like jQuery each.

I posted an identical answer on a similar question: Setting image src attribute not working in Chrome

like image 40
Vlad Sabev Avatar answered Oct 14 '22 09:10

Vlad Sabev


You can do this. First assign the image an ID

<img id='image_id' src='https://www.google.com/images/srpr/logo3w.png'>

And then remove the source attribute.

jQuery('#image_id').removeAttr('src')
jQuery('#image_id').show();
like image 21
AlanP Avatar answered Oct 14 '22 09:10

AlanP


what about simply hiding an element:

$('img').hide();

You cannot remove an image from a tag. When you use jQuery, bear in mind that you do not deal with tags, you manupulate with DOM elements. Therefore, your tag in terms of jquery is not a tag, it is an object, a DOM element. And this is element is not a tag, IT IS an element that represents an image in DOM. So if you want to hide an image, you must hide the element.

like image 30
Michael Zelensky Avatar answered Oct 14 '22 09:10

Michael Zelensky