Hide li if broken image
css, html, javascript, jquery
Solution
You can use an `onerror` handler for the image:
<li><a href='http://www.so.com'>
<img src='http://www.so.com/1.jpg' onerror='hideContainer(this)'>
</a></li>
// this function must be in the global scope
function hideContainer(el) {
$(el).closest("li").hide();
}
Or, you could even just remove it if you really want it as if it never existing in the DOM:
// this function must be in the global scope
function hideContainer(el) {
$(el).closest("li").remove();
}
If you don't want to put an `onerror` handler in the HTML (the only reliable place you can put it) then you can hide the images initially and then check `.complete` when your jQuery runs and if the image is not yet complete, then install a `.load()` handler like this:
CSS:
/* use some more specific selector than this */
li {display: none;}
jQuery:
$("li img").each(function() {
if (this.complete) {
// img already loaded successfully, show it
$(this).closest("li").show();
} else {
// not loaded yet so install a .load handler to see if it loads
$(this).load(function() {
// loaded successfully so show it
$(this).closest("li").show();
});
}
});
Problem
I have a list of images where each image is wrapped in a li: ``` <li><a href='http://www.so.com'><img src='http://www.so.com/1.jpg'></a></li> ``` How can I hide this entire li if image 1.jpg is broken as if it never existed in the DOM? I found some good js on how to hide the image and learned from another SO post that I want to `display:none` so I don't create an empty row. But I'm having trouble putting these together.