Sometimes a certain feature or coding syntax will catch you off guard. It will bring you back to Earth letting you know that you really don’t know everything about web development. For me, that was the onerror attribute of the HTML image tag.
This tag is particularly useful. Let’s say you are screen scraping HTML content on a search listing to generate an image preview, now you can remove the image element if it doesn’t exist. You know, everyone hates that annoying spacing that occurs when the image tag exists but the image doesn’t.
Here is a simple demo:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>Image Tag onerror Attribute</title>
<meta charset="UTF-8">
</head>
<body>
<img src="http://theglenbot.com/a-broken-image.jpg" onerror="this.parentNode.removeChild(this);" />
</body>
</html>
I’m not really sure if this is standard HTML but it seems to work in IE7+, Chrome 4+, and FF 3.0+.
** Update: After a comment from Jim it seems that this method is insecure and does not validate. I believe in security and web standards so I did some research and found a great article on this topic at sociomantic.
A better, more secure route would be to use jQuery to accomplish the task. Assuming you have images classed “profile-pic” you can use jQuery like this:
$(document).ready(function() {
$('a.profile-pic').error(function() {
this.src = '/images/default-profile-pic.jpg';
});
});

The ONERROR attribute doesn’t seem to be valid with XHTML Transitional. Do you know the proper Doctype?
(Thanks for posting something about this!)
It seems that there isn’t a Doctype that will validate the html. After more research a better and more secure solution is to use jQuery to trigger the reflex.
I’ll update the post to show this. Thanks!
Nice and simple