Search for image tag using alt text

I would like to know if Javascript can be used to search for an image tag in its alt text. For example, I have this tag: <img src="Myimage.jpg" alt="Myimage">would there be a way to get the tag by looking for the alt attribute "Myimage"?

+3
source share
4 answers

Undoubtedly, the jQuery solution will be published soon enough. To do this 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];
+7
source

You can do this with jQuery . The following jQuery code will return any image with the alt tag set to "Myimage":

$('img[alt="Myimage"]').

id .

+7
var imgElement = document.querySelector(img[alt="MyImage"])
+1
source

It is not so difficult if NodeList has implemented Iterable. This implementation puts the filter in a NodeList prototype that may not suit every taste, but I prefer compressed 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>
0
source

Source: https://habr.com/ru/post/1747217/


All Articles