JavaScript

Detect and Remove Broken Image Links: Optimizing img Tags with jQuery’s error() Method

In scenarios where multiple people are updating and managing a website, it is common to encounter img tags with broken image links. Broken image links can make the site appear incomplete or improperly maintained to visitors, so it’s essential to have a method to address this issue. In this post, we will detail how to automatically remove img tags with broken links using jQuery’s .error() method.

Setting Up Sample CSS

First, set up the basic design of your page using the following CSS. Feel free to customize these settings as needed.

<style type="text/css" media="all">
<!--
body{
	margin:0;
	padding:0;
}
h1{
	text-align:center;
	font-size:18px;
	font-weight:bold;
	padding:10px 0;
	line-height:1.4em;
	text-align:center;
}
p{
	width:500px;
	margin:0 auto;
	line-height:1.4em;
	padding-bottom:15px;
}
.clWrap{
	width:800px;
	margin:0 auto;
}
-->
</style>

HTML Code

Next, place sample img tags in your HTML as follows. In this example, some of the images are set to be broken links.

<div align="center">
    <img src="i1.jpg" alt="" width="300" height="300">
    <img src="i2.jpg" alt="" width="300" height="300">
    <img src="i3.jpg" alt="" width="300" height="300">
    <img src="i4.jpg" alt="" width="300" height="300">
    <img src="i5.jpg" alt="" width="300" height="300">
</div>

Automatic Removal Using JavaScript

The following JavaScript code will automatically remove img tags that encounter an error (such as when an image file is not found).

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('img').error(function() {
	// Remove img tag if the image file does not exist
        $(this).remove();
    });
});
</script>

 
This code will remove img tag elements that generate an error (e.g., when an image cannot be found) after the page loads.

Demo Page to Remove img Tags with Missing Image Files

To see this method in action, check the demo page from the link below.

Demo: Remove img Tags When Image Files Are Missing

This approach in jQuery is similar to using PHP’s file_exists function to check whether a specific file exists. If an image link is broken, an error message will also appear in the console of Chrome Developer Tools.

Summary

We have learned how to detect broken image links and automatically remove the corresponding img tags. This method can help maintain the appearance and user experience of your site without issues. It is particularly useful for sites managed by multiple people or those with many pages and images.

 
Note: Use this method at your own risk. Do not reuse the Google Analytics tag from the demo page in your projects.