'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?



Solution 1:[1]

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];

Solution 2:[2]

var imgElement = document.querySelector('img[alt="MyImage"]')

Solution 3:[3]

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.

Solution 4:[4]

This wouldn't be so hard if NodeList implemented Iterable. This implementation puts filter into the prototype of NodeList, which may not match everyones taste but I prefer concise access to my data structures.

<html>  
    <head>
        <script type="text/javascript">
            // unfortunately NodeLists do not have many of the nice Iterate functions
            // on them, here is an incomplete filter implementation
            NodeList.prototype.filter = function(testFn) {
                var array = [] ;
                for (var cnt = 0 ; cnt < this.length ; cnt++) {
                    if (testFn(this[cnt])) array.push(this[cnt]) ; 
                }
                return array ;
            }

            // loops through the img tags and finds returns true for elements that
            // match the alt text
            function findByAlt(altText) {
                var imgs = document.getElementsByTagName('img').filter(function(x) {
                    return x.alt === altText ;
                }) ;

                return imgs ;

            }

            // start the whole thing
            function load() {
                var images = findByAlt('sometext') ;

                images.forEach(function(x) {
                    alert(x.alt) ;
                }) ;
            }

        </script>
    </head>

    <body onload="load()">
        <img src="./img1.png" alt="sometext"/>
        <img src="./img2.png" alt="sometext"/>
        <img src="./img3.png" alt="someothertext"/>
    </body>
</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Down
Solution 2 Charney Kaye
Solution 3 Josh
Solution 4 Mike