Return the alternate text of an image:
var x = document.getElementById("myImg").alt;
Click the button to display the alternate text of the image.
<!DOCTYPE html> <html> <body> <img id="myImg" src="image1.png" alt="The Circle" width="100" height="98"> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() {// ww w . j ava2 s. c om var x = document.getElementById("myImg").alt; document.getElementById("demo").innerHTML = x; } </script> </body> </html>
The alt
property sets or gets the value of the alt attribute of an image.
The required alt attribute specifies an alternate text for an image, if the image for some reason cannot be displayed (because of slow connection, an error in the src attribute, or if the user uses a screen reader).
To create a tooltip for an image, use the global title attribute.
The alt
property accepts and returns a String type value.
Value | Description |
---|---|
text | Specifies an alternate text for an image. |
The alt
property returns a String representing the alternate text of the image.