The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Use document.getElementById() to retrieve one uniquely identified image, then assign its new path to src. Check that the element exists first:
const img = document.getElementById("hero");
if (img) {
img.src = "new-image.jpg";
}
Change the source of one image
Give the image an ID in your HTML, then use that exact ID in JavaScript:
<img id="hero" src="old-image.jpg" alt="A view of the mountains">
<script>
const img = document.getElementById("hero");
if (img) {
img.src = "new-image.jpg";
}
</script>
getElementById() returns the element whose ID matches the string you pass. The MDN reference documents this lookup method. An image element exposes its source through the src property; see MDN’s HTMLImageElement reference.
Make sure the lookup matches
- IDs should be unique in the document, so an ID lookup is for one element, not a group.
- The ID string is case-sensitive:
"hero"does not matchid="Hero". - The method name is exactly
getElementById. If there is no match, it returnsnull; the existence check prevents trying to setsrcon a missing element.
Apply the change to several images
getElementById() is not a multi-element selector. If several images should receive the same source, give them a shared class and use querySelectorAll() to select and iterate over that set:
#1 Best Overall
<img class="gallery-image" src="one.jpg" alt="First view">
<img class="gallery-image" src="two.jpg" alt="Second view">
<script>
document.querySelectorAll("img.gallery-image").forEach((img) => {
img.src = "new-image.jpg";
});
</script>
Choose a selector that identifies only the images you intend to change. MDN describes DOM selection and traversal methods, including selectors that can return multiple matches.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Review the alternative text
Keep the alt text useful: it matters when an image cannot be displayed. If the replacement changes what the image communicates, update the alternative text to match. See MDN’s <img> reference.
Quick Recap
Best Value
Rank #4
Rank #2
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




