Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an image tag using the alt text

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?

like image 739
MrJackV Avatar asked May 26 '10 15:05

MrJackV


People also ask

How do I find an image with alt text?

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.

What is an alt tag for an 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).

Can a tag have alt text?

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.


3 Answers

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];
like image 189
Tim Down Avatar answered Oct 01 '22 23:10

Tim Down


var imgElement = document.querySelector('img[alt="MyImage"]')
like image 42
Stephan Heilner Avatar answered Oct 02 '22 00:10

Stephan Heilner


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.

like image 45
DanielC Avatar answered Oct 01 '22 23:10

DanielC