Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

HTMLImageElement.src — image source URL

HTMLImageElement.src reads or sets an image URL. It reflects the src attribute. Reading it returns an absolute URL only if the attribute value parses successfully using the document's base URL. It does not confirm that the image has loaded.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

image.src = url;
const resolvedUrl = image.src;

HTMLImageElement.src is a writable string property of the browser DOM, not ECMAScript itself. It reflects the src attribute of an img element: assigning image.src = url changes that attribute.

If the attribute is present, reading image.src returns an absolute URL only if the attribute value parses successfully using the document's base URL. If URL parsing fails, image.src returns the attribute value as a USVString. Any lone UTF-16 surrogate stored in the attribute, for example through setAttribute, is replaced with the replacement character U+FFFD in the returned string. For example, icon.png cannot be resolved against an opaque data: base URL. If the attribute is absent, image.src returns an empty string. In contrast, image.getAttribute("src") returns the stored attribute value without URL resolution, or null when the attribute is absent.

Changing src triggers image-source processing but does not mean loading finishes immediately. Handle load and error events, installing handlers before assignment. With srcset or picture, the selected resource can differ from src; use currentSrc to inspect the current request's URL.

The example tests only URL resolution in a separate document with a fixed base. It does not test image fetching or display. Run it in a browser; Node 24 being present in a repository does not establish support for this API.

Examples

const doc = document.implementation.createHTMLDocument("Demo");
const base = doc.createElement("base");
base.href = "https://example.invalid/assets/";
doc.head.append(base);

const image = doc.createElement("img");
image.src = "icon.png";

console.log(image.getAttribute("src"));
console.log(image.src);

Result

icon.png
https://example.invalid/assets/icon.png

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources