Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all empty <img src=""> on a page with JavaScript on dom loaded?

I need a function, that starts, when the DOM is loaded.

In my HTML Page are several empty Image Tags, like and I want to add an Image-Name into the src-property when everything is loaded to get something like

<img src="blank.jpg">.

Best wishes Chris

like image 674
ChrisBenyamin Avatar asked Jul 16 '10 19:07

ChrisBenyamin


3 Answers

Construction <img src=""> is invalid. Never use it.

It's invalid because empty url means url to current page. But current page is HTML document, not image. Browser can make another query of current page and try to use it as image (see this page).

like image 156
Pavel Strakhov Avatar answered Nov 10 '22 00:11

Pavel Strakhov


function replaceSrc()
{

    var images = document.getElementsByTagName('img');

    for(var i = 0; i < images.length; i++)
    {
        var img = images[i];

        if(img.src.length == 0)
        {
            img.src = 'blank.jpg';
        }
    }
}


window.onload = replaceSrc;

OR if you want to add more than one handler for the event:

document.addEventListener('load', replaceSrc, false) //W3C
document.attachEvent('onload', replaceSrc); //IE

With jQuery

   $(document)
     .ready(function() { $('img')
                             .filter(function(){ return this.src.length == 0 })
                                 .each(function () { this.src = 'blank.jpg'})  });

EDIT:

I realized that you probably want to set the src property before the images load so I changed the code to fire on the document's load event, which happens before the images start loading.

like image 28
Rodrick Chapman Avatar answered Nov 09 '22 22:11

Rodrick Chapman


Use jQuery! It's easy.

$('img').attr('src','new-image-name.jpg')

This will set the src attribute of every img tag to 'new-image-name.jpg'.

like image 34
advait Avatar answered Nov 10 '22 00:11

advait