What is the best way to change an image using JavaScript?

Is there a way to change an image when the tag doesn't have an id?

<img src="URL_1" />

I need to replace URL_1 with URL_2

Any suggestions on how to do this?

Answer №1

Need to update an image URL?

document.querySelector('img[src="URL_1"]').src = "URL_2";

If the URL is unknown but there's an id, you can do this:

<img id="id" src="URL_1" />

document.getElementById("id").src = "URL_2";

Answer №2

If this image is the only one on the page, you can easily access it using the Element.getElementsByTagName() method to manipulate its source:

document.getElementsByTagName('img')[0].src = 'NEW_URL'

Alternatively, consider utilizing the Selectors API for targeting elements in a more detailed manner using CSS selectors:

document.querySelectorAll('img')[0].src = 'NEW_URL'

Answer №3

If you're unable to include an id or a class, consider enclosing your img tag within a div and using greater specificity like div .myclass img. Another option would be to target the img tag by its source URL, such as: img[src="URL_1"]

Answer №4

Assigning an identifier

<img id="uniqueImgID" src="oldURL"   />

Next steps

document.getElementById('uniqueImgID').setAttribute('src', 'newURL');

Answer №5

Start by giving your image an identifier

HTML snippet

<img id="image_id" src="photo.jpg"/>

JavaScript code using JQuery

$("#image_id").attr("src","new_photo.jpg");

Alternatively, without relying on JQuery

document.getElementById("image_id").src="new_photo.jpg";

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

Toggle visibility (individually duplicating) one thousand sentences while maintaining optimal browser and host performance

I have created JQuery scripts to toggle the display of future sentences on my page (approximately 1000 duplicates) and I am seeking the most efficient method (for browser/host) to accomplish this task. Here are two functional solutions that I have already ...

How come the <script> element is showing up in the <body> tag even though I initially declared it outside the <body>

I'm currently working on web projects through the Odin Project and I want to follow the software engineering process by taking small steps and testing them. Specifically, I'm interested in seeing the output of document.querySelector("body"). I kn ...

Bootstrap 4 Nav Table of Contents with Expand and Collapse Feature

Currently, I am encountering an issue with implementing a button to expand and collapse a "table of contents" in Bootstrap 4. The code I have so far can be viewed here: https://codepen.io/nht910/pen/RwwwyKB Code Snippet: <div class="main-wrapper col- ...

Create a script that ensures my website can be set as the homepage on any internet browser

I am currently in search of a way to prompt users on my website to set it as their homepage. Upon clicking "Yes," I would like to execute a script that will automatically make my website the user's browser homepage. I have come across a Similar Thread ...

Which specific events must I manage within the express response (stream) object to ensure proper handling when the response is completed?

I'm looking to automate the logging process for when a request completes. Here's an example of what I have so far: function (req, res, next) { var startTime = clock.now(); res.on('end'. function() { logger.trace("E ...

How can I properly redirect an HTTP request to HTTPS on my Express server?

Currently, I am working on my API and have configured it to work with the HTTPS protocol using SSL. Here is the code snippet: https.createServer({ key: fs.readFileSync(certKeySSLPath), cert: fs.readFileSync(certSSLPath) }, app).listen(serverPORTHTT ...

Attempting to iterate over a JSON object and display its contents using HTML

I have been attempting to iterate through this JSON data and display it in an accordion format similar to the one shown here: but unfortunately, my implementation is not functioning correctly. Here is what I currently have: HTML: <div class="a ...

An issue has been detected in the constants.json file located in the constants-browserify

I organized my folders into client-side and server-side categories, but I failed to work from a parent folder perspective. Now, as I attempt to deploy to Heroku, I realize that I need one main folder for the deployment process. To address this issue, I dec ...

Having trouble with WordPress jQuery Click function. Would greatly appreciate some assistance :)

There seems to be a mix of working and non-working jQuery code. Specifically, the click function is not functioning properly in this case. Here is an example of the code that works: $j=jQuery.noConflict(); // Using jQuery with $j(...) $j(document ...

Methods to maintain the select2 dropdown event open while interacting with another select2 dropdown

I have a situation where I need to dynamically add a class to a div whenever a select2 dropdown is open. To achieve this functionality, I am utilizing the open and close events of select2. The current code successfully adds the class when opening a selec ...

Is there a way to customize the CSS ul menu specifically for the JavaScript autocomplete feature?

I have created a search page with autocomplete for the first textbox, but I noticed that the ul/li CSS classes used for styling the main menu are impacting the JavaScript list. How can I override the menu styling to display a regular list format? Being a ...

Is there a way to change the border property of an element when clicked, without causing the displacement of other elements?

I'm in the process of creating a webpage where users can choose the color and storage capacity of an item. Only one color/capacity can be selected at a time, and once chosen, it should be highlighted with a border. The issue I encountered is that whe ...

Ways to move code from a route to a component

My question is about the routing setup: <BrowserRouter> <Navbar /> <div className="container pt-4"> <Switch> <Route path="/" exact component ...

Leveraging server-sent events to retrieve an array from a MySQL database using PHP

I've been attempting to implement server-sent events in order to fetch data from a database and dynamically update my HTML page whenever a new message is received. Here's the code I'm using: function update() { if(typeof(Event ...

The performance of Javascript versus Java on PlayN varies significantly

After building the PlayN project and running the Java version, I noticed that its behavior is not consistent with the HTML version. I created a board game that utilizes a customized Minimax algorithm for its AI, which includes a search tree and evaluation ...

What is the best way to ensure that the circle is perfectly centered inside the box?

Currently delving into the world of game programming, I've been struggling with this exercise. I can't seem to figure out why the circle won't stop in the center of the box within the update function. What am I missing? var canvas = documen ...

Is it possible to eliminate the border of an HTML element when clicked, while still keeping the border intact when the element is in

I am currently developing a project with an emphasis on Web accessibility. Snippet of Code: function removeBorder(){ li=document.getElementById("link"); li.classList.add(".remove") } body{ background:#dddddd; } p:focus{ border:1px solid red; } li{ ...

What is the best way to remove the background transparency of an image?

Images are being shown inside an HTML table using PHP code : This is the code for the table : for ($i = 0; $i < $data['list']['cnt']; $i++) { $tabRows[$i][1]['width'] = "45%"; $tabRows[$i][1][&apos ...

Is it possible to use the .on() event handler within an ajaxComplete

After implementing this code: $('.task').on('click', function() { task_id = $(this).data('id'); console.log('Task id: ' + task_id); }); The functionality doesn't behave correctly when the content is re ...