Remove missing images (and parent elements) using jQuery

My client has an auto dealership site where inventory images are pulled remotely, i.e. 'hotlinked', from the inventory service's website. The client asked me to create a slideshow of inventory images on the home page - no problem using jQuery cycle() plugin - but there's one hangup: some of the images don't exist!  Easy enough to remove the images ( <img onerror="this.style.display = 'none'"> ) , but these images are dynamically linked, and contained in an unordered list. So, even if I remove the errant images with an inline attribute, I still have this empty 'a' and 'li' hanging around.

Using a single line of jQuery code, I whipped up this super-quick solution:

<script type="text/javascript">
$(document).ready(function(){

// find all missing images
$('#slideshowWrap img').error(function(){

// hide the image, then remove the parent element from the DOM
$(this).hide().parents('a').parents('li').remove();

// uncomment line below to see the script at work
//alert('hidden: ' + $(this).attr('src'));

});

// end jquery
});
</script>


The parents('a') could become parents('p') or whatever is needed to get rid of the containing element.

Maybe the 'hide()' combined with 'remove()' is redundant.... but I like it.

That 'alert' line, if uncommented, will alert you to the src of each missing image for testing.


Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
What I usually do is, in the error() event bind I change the SRC attribute of the image to a generic "Sorry, thumbnail temporary unavailable" image:
$('img').error(function(){ $(this).attr('src', '/images/error.png'); });

you could also just add an onerror attribute to the img tags with this.src='/images/error.png' as its value, but that will make the code non-compliant with xhtml standards...

Azadi
# Author Azadi Saryev | 6/24/09 4:37 AM
@azadi In this case I needed to not only remove the image (don't need any 'sorry' images in my slideshow) but also remove the parent elements. 'onError' won't do that.
# Author Michael Evangelista | 6/24/09 11:27 AM
blogcfc 5.9.1.002 by raymond camden
contact michael evangelista