Enter text and click the button. The image's alt and title values are updated, and the entered text is shown below.
Return to tutorial on image alt tag
const image = document.getElementById('i1');
const input = document.getElementById('t1');
const button = document.getElementById('change-alt');
const output = document.getElementById('d1');
button.addEventListener('click', () => {
const text = input.value.trim();
image.alt = text;
image.title = text;
output.textContent = text;
});
<img src="images/help.jpg" id="i1" alt="Default alt text" width="50" height="50">
<input type="text" id="t1" size="50" aria-label="New image alt text">
<button type="button" id="change-alt">Change Alt</button>
<p>Here is the text you entered:</p>
<div id="d1" aria-live="polite"></div>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change image alt text with JavaScript</title>
</head>
<body>
<img src="images/help.jpg" id="i1" alt="Default alt text" width="50" height="50">
<br><br>
<input type="text" id="t1" size="50" aria-label="New image alt text">
<button type="button" id="change-alt">Change Alt</button>
<p>Here is the text you entered:</p>
<div id="d1" aria-live="polite"></div>
<p>Return to <a href="image-alt.php">tutorial on image alt tag</a></p>
<script>
const image = document.getElementById('i1');
const input = document.getElementById('t1');
const button = document.getElementById('change-alt');
const output = document.getElementById('d1');
button.addEventListener('click', () => {
const text = input.value.trim();
image.alt = text;
image.title = text;
output.textContent = text;
});
</script>
</body>
</html>