I would like to know if it was possible using Javascript to find an image tag by its alt text. For instance I have this tag: <img src="Myimage.jpg" alt="Myimage">
would there be a way to obtain the tag by looking for the "Myimage" alt attribute?
Chrome™ browser: point to the image with your mouse, right-click and choose Inspect from the quick menu (or use Ctrl-Shift-I on keyboard). A new pane will open at the right of your screen with the HTML code highlighted for that element. You can then view the alt text and other attributes for the image.
The required alt attribute specifies an alternate text for an image, if the image cannot be displayed. The alt attribute provides alternative information for an image if a user for some reason cannot view it (because of slow connection, an error in the src attribute, or if the user uses a screen reader).
No, an alt attribute (it would be an attribute, not a tag) is not allowed for an a element in any HTML specification or draft.
There will undoubtedly be a jQuery solution posted soon enough. To do it without, the following will work:
function getImagesByAlt(alt) {
var allImages = document.getElementsByTagName("img");
var images = [];
for (var i = 0, len = allImages.length; i < len; ++i) {
if (allImages[i].alt == alt) {
images.push(allImages[i]);
}
}
return images;
}
var myImage = getImagesByAlt("Myimage")[0];
var imgElement = document.querySelector('img[alt="MyImage"]')
You can do this with JQuery. The following JQuery code will return any image with the alt tag set to "Myimage":
$('img[alt="Myimage"]').
However it would be a lot easier and a lot more performant to use the id attribute of the image tag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With