HOWTO · JavaScript
How to Display Image With JavaScript
Learn to display images with JavaScript by changing an existing image, creating an img element, or responding to user input, with practical path and accessibility guidance.
On this page
To display an image with JavaScript, either update the src of an existing HTML <img> element or create an image element and append it to the page. Use the first approach when replacing an image in place; create a new element when adding an image to a gallery or another container. In both cases, JavaScript changes the page’s DOM, while the browser loads the image identified by its source.
Change the source of an existing image
Start with an image in the HTML and give it an ID. A button can update its src property when clicked. This complete browser-page example expects image1.jpg and image2.jpg to be available at the shown paths relative to the page:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Change an image</title>
<img id="photo" src="image1.jpg" alt="A view of the coast">
<button id="change">Show the second photo</button>
<script>
const photo = document.querySelector("#photo");
document.querySelector("#change").addEventListener("click", () => {
photo.src = "image2.jpg";
photo.alt = "A view of the mountains";
});
</script>
</html>
Changing src asks the browser to load the new resource; it does not replace or reload the whole page. Update alt too when the new image has different meaningful content. If the image is decorative and adjacent text already conveys the same information, use an empty alt value instead of repeating that text.
Create and append a new image element
Use document.createElement("img") to make an <img> element, set its source and alternative text, then append it to the container where it should appear. The following static browser-page example uses a reusable helper and adds one image each time the button is pressed. It expects images/sunset.jpg to resolve from the page’s location.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Add an image</title>
<button id="add">Add photo</button>
<div id="gallery"></div>
<script>
function addImage(source, description, container) {
const image = document.createElement("img");
image.src = source;
image.alt = description;
container.appendChild(image);
}
const gallery = document.querySelector("#gallery");
document.querySelector("#add").addEventListener("click", () => {
addImage("images/sunset.jpg", "Sunset over the water", gallery);
});
</script>
</html>
width and height are optional. Set them when a known display size helps reserve layout space, or style the image with CSS. A width property on an image is measured in CSS pixels. For responsive layouts, CSS such as max-width: 100%; height: auto can keep the image within its container while preserving its proportions.
Run this JavaScript example to see how a known selection maps to an image path. It is a small executable illustration of the source-selection step; the browser-page examples above show the DOM operations.
const imagePaths = {
coast: "images/coast.jpg",
mountain: "images/mountain.jpg"
};
const selectedImage = imagePaths.coast;
console.log(selectedImage);
Display an image based on user input
For a dropdown, keep each option’s value set to a known image path or URL. Read the selected value and update an existing image. This browser-page example expects the two files under images/ relative to the page:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Select an image</title>
<label for="image-choice">Choose a scene:</label>
<select id="image-choice">
<option value="images/coast.jpg">Coast</option>
<option value="images/mountain.jpg">Mountain</option>
</select>
<img id="preview" src="images/coast.jpg" alt="Coastal scene">
<script>
const choices = document.querySelector("#image-choice");
const preview = document.querySelector("#preview");
const descriptions = {
"images/coast.jpg": "Coastal scene",
"images/mountain.jpg": "Mountain scene"
};
choices.addEventListener("change", () => {
preview.src = choices.value;
preview.alt = descriptions[choices.value];
});
</script>
</html>
The option values are fixed by the page, so the user selects only a source you provide. If values come from another source, validate them against an allowed list before assigning them. For file uploads, use a file input and create a temporary object URL from the selected File; revoke that URL when it is no longer needed. A local file path typed by a user is not generally a URL that a page can read directly.
Handle paths, loading, and accessibility
<img> is an HTML element, not a JavaScript tag. JavaScript creates its DOM representation with document.createElement; src is the image’s source property (and corresponds to the src attribute), not a method. A path can be relative or absolute. Relative paths resolve from the document URL, which may differ from the folder where a script file lives. A root-relative path starts at the site’s root; an absolute URL includes its scheme and host.
If an image is missing, inspect the element’s current src in browser developer tools and open that URL directly. Check spelling, capitalization, the page’s URL, deployment directory, server response, and network or console messages. A failed image request usually appears as a broken image and a network error; it is distinct from a JavaScript exception such as querying an element before it exists. Place scripts after the relevant markup or wait for the DOM before querying it. The load and error events can also help diagnose whether the browser fetched and decoded an image.
Write concise alt text describing the image’s useful content, not its filename or path. An ordinary cross-origin image can often be displayed by setting its URL as src; CORS permission is relevant for restricted operations such as reading cross-origin image pixels through a canvas. The remote server and browser policies still determine whether a particular resource can load.
FAQ
- How do I change an image with JavaScript? Select its existing
<img>element and assign a new value tosrc. Updatealtwhen the image’s meaning changes. - Can JavaScript add several images? Yes. Create an
<img>for each source and append each one to a gallery or other container. Use a loop when the sources are already in an array. - How can a user choose which image appears? Read a dropdown or other control’s value in its
changeevent and set the preview image’ssrcto an allowed source. - Can I use an external image URL? Yes, if the URL is reachable and the server permits the browser request. Displaying an image alone does not generally require CORS access; reading its pixels through canvas has additional cross-origin restrictions.
- Why is the image missing? Confirm the resolved URL and file name, then check the browser’s Network and Console panels for a failed request or script error. Verify that the file is deployed where that URL points.