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.
