Finding An image tag using the alt text

前端 未结 4 1403
终归单人心
终归单人心 2021-01-02 16:54

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: \"Myimage\

相关标签:
4条回答
  • 2021-01-02 17:18

    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];
    
    0 讨论(0)
  • 2021-01-02 17:24
    var imgElement = document.querySelector(img[alt="MyImage"])
    
    0 讨论(0)
  • 2021-01-02 17:34

    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>
    
    0 讨论(0)
  • 2021-01-02 17:36

    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.

    0 讨论(0)
提交回复
热议问题