Making a switch from one image to another - JavaScript

I need a solution to swap out an image that is used in multiple locations on a webpage.

Consider this sample HTML page:

<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>

Wherever the URL example.com/img/1889.png is found, it needs to be replaced with something different.

UPDATE

Regrettably, I am restricted from using any JavaScript libraries as this is for a browser extension. Additionally, browser-specific APIs cannot be utilized.

Answer №1

If you encounter any syntax errors, consider using this example as a guide:

<script>
    var images = document.getElementsByTagName("img");
    for (var index = 0; index < images.length; index++) {
        if (images[index].src == "oldImage")
            images[index].src = "newImage";
        }
    }
    var containers = document.getElementsByTagName("div");
    for (var index = 0; index < containers.length; index++) {
        if (containers[index].style.backgroundImage == "oldImage")
            containers[index].style.backgroundImage = "newImage";
        }
    }
</script>

Answer №2

Here is a snippet of code that accomplishes the task you are seeking:

let allImages = document.querySelectorAll('[src]'), // selects all image and input elements
    styledElements = document.querySelectorAll('[style]'), // grabs all elements with inline styling
    imgLength = allImages.length,
    styleLength = styledElements.length,
    searchUrl = 'example.com/img/1889.png', // defines the URL string to look for
    newString = 'different/string', // choose your replacement string here
    count;

// check if 'example.com/img/1889.png' is in any image source attribute
for (count = 0; count < imgLength; count++) {
    if (allImages[count].src.includes(searchUrl)) {
        allImages[count].src = newString;
    }
}

// check if 'example.com/img/1889.png' is in either background or background-image style properties
for (count = 0; count < styleLength; count++) {
    if (styledElements[count].style.backgroundImage.includes(searchUrl)) {
        styledElements[count].style.backgroundImage = 'url(' + newString + ')';
    }
}

View Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the presence of a white border in the footer section?

I am trying to create a div in the footer that sits side by side, but the current code is causing it to have an unwanted white border. <!DOCTYPE html> <html lang="en"> <head> <style type="text/css"> #botto ...

The error message displayed reads as follows: "topojson has encountered a TypeError: Unable to access the property 'feature' as

Context A problem has arisen with JavaScript when trying to use the topojson.feature(topology, object) function. It seems that this issue appeared after moving from TopoJSON version 1.6.26 to version 2.x, although the functionality remains similar. The p ...

Why is the jQuery not functioning within the AngularJS function?

I am encountering an issue with writing jQuery inside an AngularJS function. I can't seem to figure out why it's not working properly. HTML <div> <span ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showD ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; https://i.sstatic.net/p0Foo.p ...

What could be causing Django REST Framework to block non-GET requests with a 403 Forbidden error from all devices except for mine?

Currently in the process of developing a web app using a Django REST Framework API. It runs smoothly on the computer where it was created (hosted online, not locally), but when trying to access the website from another computer, all GET requests work fine ...

The function this.listCatModel.push is not a valid operation

I have a dropdown that I want to populate using the following code: this.categoryService.GetListItem(this.GetAllcatListUrl).subscribe(data=>{ this.listCatModel=data, this.listCatModel.push({ id:0, name:'Main Category', parent ...

Tips for utilizing the for each function within a for loop

Looking to showcase prices alongside each product based on their unique sku value, I've put together a price list. An array of data is being iterated through and pushed into the div container. var arr = [ { "sku": "552", "title": "orange", "pric ...

Encountering an issue: Module not found - 'cryptile' during express js installation

Just dipping my toes into the world of Node.js and I'm encountering some obstacles when trying to install Express.js. Seeking assistance in resolving this issue and successfully setting up Express.js. https://i.stack.imgur.com/PlHiB.png Interestingl ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

Unresponsive HTML button

I'm currently developing an interactive text-based game that relies on button functionality to change text content. Everything was functioning perfectly until just a few moments ago, but now it has inexplicably stopped working. Here is the section of ...

Use Ramda to convert an array of objects into nested objects

As a beginner, please forgive me for asking what may be considered a naive question. I currently have an array of objects const arr = [{id: 1, name: 'Pete'}, {id: 5, name: 'John'}, {id: 3, name: 'Peter'}] and I am looking to ...

Mastering the art of looping through JSON values using AngularJS ng-repeat

Is there a way to use ng-repeat in order to iterate and access the name values: test01, test02, and test03 from my JSON data? Any guidance on how to achieve this using ng-repeat would be greatly appreciated. Thanks in advance! Check out this Fiddle link. ...

What is the best way to animate various sprites using distinct buttons in HTML and CSS?

I've been experimenting with animating a sprite by using different onClick button triggers. I encountered an issue where only one of the buttons works correctly in the fiddle. However, in my local file version, the other buttons work but only once and ...

Middleware in Express.js designed to alter the response object

One method I'd like to explore is using middleware functions to alter the response. app.use(function(request, response, next) { .. do something .. next(); // moves to next middleware }); When it comes to modifying the request and response ob ...

What is the method to activate a select event on a particular row using Google visualizations?

Currently, there is a single table where clicking on a row should simulate the same action on another GV table. The code for the listener is as follows: $(".mytable tbody tr td").click(function() { var colIndex = $(this).parent().children().index($(th ...

Using jQuery to Capture Datepicker Input and Assigning to PHP Variable

I need help figuring out how to save a jQuery datepicker value in a php date formatted variable. My goal is to have: input field named "reviewdate" = 03/02/2015 input field named "reviewmonth" = 3 Both values should be stored in a mysql database. I am ...

Expanding parent nodes in Jstree to load child nodes dynamically (json)

I am trying to optimize the performance by loading the child nodes of a parent node only after clicking on that specific parent node. It is important because there are many child nodes, so this method helps in keeping the performance high. Currently, I ha ...

Is it possible to pass a component into a dialogue box in material-ui using React?

Hello, I am currently facing an issue with displaying a chart component within a dialogue box. Despite having the code in place, the chart is not rendering inside the dialogue box as expected. Unfortunately, due to the complexity of the code, I am unable t ...

Utilizing the Input method in Node.js

Transitioning from Python 3 to Node.js has me wondering if there is a similar function in Node.js to Python's input. For example, consider this code snippet: function newUser(user = null, password = null) { if (!user) user = prompt("New user name ...

Design a customizable input field to collect HTML/JS tags

I'm looking to incorporate a similar design element on my website. Can anyone offer me some guidance? Check out the image here ...