November 6, 2023
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.
If your image has an id attribute, you can use
For more complex selectors,
querySelector is very handy:
Using getElementsByTagName or getElementsByClassName
You can also get images by their tag name or class name:
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
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.
Handling relative and absolute URLs
When changing the src attribute, you can use either relative or absolute URLs:
If you want to change an image without any visible delay, consider preloading it:
When changing the src to an image from a different domain, be aware of cross-origin restrictions and set appropriate CORS headers if necessary.
Always consider what should happen if the new image fails to load:
Adding an event listener for errors
When changing an image src, remember to update the
alt text if the new image conveys different content:
Updating image sources dynamically
Changing src on a user event
How to Truncate Date in MySQL