Switch an Image’s Alt Text Between Languages with JavaScript

Last updated: December 5, 2026.

When a visitor switches languages, assign the translated text to the image’s alt property and set lang on the same element. The alternative does not normally replace a successfully loaded image on screen.

const image = document.querySelector('#route-map');
const toggle = document.querySelector('#turkish-alt');

const altText = {
  en: 'Map showing the route to the station',
  tr: 'İstasyona giden yolu gösteren harita',
};

function setAltLanguage(language) {
  image.alt = altText[language];
  image.lang = language;
  toggle.setAttribute('aria-pressed', String(language === 'tr'));
}

setAltLanguage('en');
toggle.addEventListener('click', () => {
  setAltLanguage(image.lang === 'tr' ? 'en' : 'tr');
});

Provide meaningful HTML before the script runs

Give the image the ID route-map, a valid source and its English alternative in the initial HTML. Add a native button with ID turkish-alt, a fixed label such as Türkçe and type="button". Load the script after the elements or use an external script with defer. The pressed state indicates which language option is active.

Use an equivalent description in both languages. Leave a decorative image’s alternative empty. If the page already has a language switcher, call the same update from it and keep the image in step with the surrounding content.

Verify the text alternative in the browser

Inspect the image in developer tools after switching twice. The alternative and the language should change together, and the image should continue to display. Check the accessible name in the accessibility inspector, then navigate back to the image with a screen reader to verify pronunciation where the chosen voice supports it.

Use a caption or nearby text for a translation people need to read on screen. On its own, changing alt does not guarantee an immediate screen reader announcement.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov