Dustin Silk
Dustin Silk

Reputation: 4620

Replace an image wherever it is used - Javascript

I'm looking for a way to replace an image that could be used anywhere on a page.

So if we have an example html page like this:

<html>
   <head>
   </head>

   <body>

       <img id="1" src="example.com/img/1889.png">

       <div style="background: url('example.com/img/1889.png')">
       <div>

       <a>
           <img id="2" src="example.com/img/1889.png">
       </a>

   </body>

</html>

Where ever - example.com/img/1889.png - appears, it must be replaced with something else.

EDIT

Unfortunately I can't use any javascript libraries. Its for a browser plugin. Nor can I use browser specific APIs

Upvotes: 1

Views: 116

Answers (2)

Derek Henderson
Derek Henderson

Reputation: 9706

The following code does what you're looking for:

var images = document.querySelectorAll('[src]'), // all image and input elements
    styled = document.querySelectorAll('[style]'), // all elements with inline style
    iLen = images.length,
    sLen = styled.length,
    url = 'example.com/img/1889.png', // the string you're searching for
    str = 'some/string', // replace with whatever you choose
    i;

// check for 'example.com/img/1889.png' in image source
for (i = 0; i < iLen; i += 1) {
    if (images[i].src.indexOf(url) !== -1) {
        images[i].src = str;
    }
}

// check for 'example.com/img/1889.png' in either background or background-image
for (i = 0; i < sLen; i += 1) {
    if (styled[i].style.backgroundImage.indexOf(url) !== -1) {
        styled[i].style.backgroundImage = 'url(' + str + ')';
    }
}

Demo

Upvotes: 1

nl-x
nl-x

Reputation: 11832

There might be some syntax errors here, but basically just try something like:

<script>
    var imgs = document.getElementsByTagName("img");
    for (var i = 0; i < imgs.length; i++) {
        if (imgs[i].src == "oldImg")
            imgs[i].src = "newImg";
        }
    }
    var divs = document.getElementsByTagName("div");
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].style.backgroundImage == "oldImg")
            divs[i].style.backgroundImage = "newImg";
        }
    }
</script>

Upvotes: 4

Related Questions