jquery – How to add a CSS class to images that didn't load?


I have an HTML page with lots of images that look like this:

<img alt="img1" width="50" height="120" src="my_image.jpg" />
<img alt="img2" width="50" height="120" src="another_image.jpg" />
<img alt="img3" width="50" height="120" src="yet_another_image.jpg" />

If any of the images doesn't load for reason A or B, there will be breaks in the layout or in some browsers, the square of the image will appear with the alternative text, making the whole appearance a little ugly.


How can I through jQuery add a CSS class to images whose loading action failed?


<img alt="img1" width="50" height="120" src="my_image.jpg" class="failToLoad" />


The most "natural" way would be to use onerror (jQuery: error ), but care must be taken as this event will only be caught if it occurs after the handler has already been added. Therefore, a solution would be to place the script that adds the class at the beginning of the document ( head , or beginning of body – before any img ). In order not to get too heavy, a solution without jQuery:

<script type="text/javascript">
function erro(elemento) { 
    elemento.className += ' failToLoad'; // Adiciona a classe às já existentes, se houver
<img src="..." onerror="erro(this)" />

Example in jsFiddle .

An alternative way, based on this answer in the English OS, seems to work correctly if you need to put the JavaScript at the end (in the document's onLoad , for example).

$('img').each(function() {
    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {

Example . The advantage of this technique is that no changes are needed to the HTML tags.

Scroll to Top