To get the
alt value of an image using jQuery, you need to use the
.attr() function. This function gets the attribute value for only the first element in the matched set. It returns undefined for values of undefined elements.
Here's a basic example:
In this example,
$('img') selects all the image elements on the page. The
.attr('alt') method then gets the
alt attribute value of the first image found. The value is stored in the
altValue variable and printed out to the console with
Please note: If there are multiple images and you want to get
alt text from a specific image, you should give that image an ID or class and select it accordingly.
For instance, if you have an image with an ID of 'myImage':
You could then get the
alt text with the following jQuery code:
In this second example,
$('#myImage') selects the image element with the ID of 'myImage'. The rest of the code functions just as before, getting the
alt attribute value and logging it to the console.
Remember to link the jQuery library in your HTML file (usually in the
<head> section), like so: