The alt
property sets or gets the value of the alt attribute of an image.
The alt
attribute of img tag specifies an alternate text for an image,
if the image cannot be displayed.
To create a tooltip for an image, use the global title
attribute.
alt |
Yes | Yes | Yes | Yes | Yes |
Return the alt property.
var v = imageObject.alt
Set the alt property.
imageObject.alt=text
Value | Description |
---|---|
text | Specifies an alternate text for an image. |
A String type value representing the alternate text of the image.
The following code shows how to get the alternate text of an image.
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" alt="test" width="100" height="100">
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from ww w. ja v a 2s. com-->
var x = document.getElementById("myImg").alt;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to change the alternate text of an image.
<!DOCTYPE html>
<html>
<body>
<!-- www .ja v a 2 s . c om-->
<img id="myImg" src="http://java2s.com/style/demo/border.png" alt="text" width="100" height="100">
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("myImg").alt = "newAlternateText";
document.getElementById("demo").innerHTML = "test";
}
</script>
</body>
</html>
The code above is rendered as follows: