How to change an image src with JavaScript
Changing the source (src) of an image in JavaScript allows for dynamic content updates without reloading the page. JavaScript provides a straightforward method to alter image elements directly in the DOM. This guide covers how that works.
Accessing the image element
Before you can change the src of an image, you need to access the image element in the DOM. You can do this using various methods provided by the document object.
Using getElementById
If your image has an id attribute, you can use getElementById
:
var image = document.getElementById('imageId');
Using querySelector
For more complex selectors, querySelector
is very handy:
var image = document.querySelector('#imageId'); // using an ID var image = document.querySelector('.imageClass'); // using a class var image = document.querySelector('img[src="original.jpg"]'); // using attribute
Using getElementsByTagName or getElementsByClassName
You can also get images by their tag name or class name:
var images = document.getElementsByTagName('img'); var image = images[0]; // gets the first image var imagesByClass = document.getElementsByClassName('imageClass'); var image = imagesByClass[0]; // gets the first image with the specified class
Changing the src attribute
Once you have a reference to the image element, you can change its src attribute simply by setting the src
property on the element.
Directly setting the src property
image.src = 'new-image.jpg';
Setting src with a function
If you're changing the src in response to an event or condition, you may want to encapsulate the logic in a function.
function changeImageSrc(newSrc) { var image = document.getElementById('imageId'); image.src = newSrc; }
Handling relative and absolute URLs
When changing the src attribute, you can use either relative or absolute URLs:
Relative URL
image.src = 'images/new-image.jpg'; // Relative to the current location
Absolute URL
image.src = '<https://example.com/images/new-image.jpg>'; // Absolute URL
Preloading images
If you want to change an image without any visible delay, consider preloading it:
Preloading with JavaScript
var preloadImage = new Image(); preloadImage.src = 'new-image.jpg'; preloadImage.onload = function() { image.src = this.src; };
Cross-origin considerations
When changing the src to an image from a different domain, be aware of cross-origin restrictions and set appropriate CORS headers if necessary.
Error handling
Always consider what should happen if the new image fails to load:
Adding an event listener for errors
image.onerror = function() { // Handle the error, perhaps set a default image this.src = 'default-image.jpg'; };
Ensuring accessibility
When changing an image src, remember to update the alt
text if the new image conveys different content:
image.alt = 'New image description';
Updating image sources dynamically
JavaScript can interact with user events to change image sources dynamically, enhancing the user experience:
Changing src on a user event
var button = document.getElementById('changeImageButton'); button.addEventListener('click', function() { changeImageSrc('new-image.jpg'); });
Invite only
We're building the next generation of data visualization.
How to Remove Characters from a String in JavaScript
Jeremy Sarchet
How to Sort Strings in JavaScript
Max Musing
How to Remove Spaces from a String in JavaScript
Jeremy Sarchet
Detecting Prime Numbers in JavaScript
Robert Cooper
How to Parse Boolean Values in JavaScript
Max Musing
How to Remove a Substring from a String in JavaScript
Robert Cooper