javascriptattributesalt

add Alt Attribute to all Images - Vanilla Javascript


How would I be able to loop through all the images, retrieve the image title, then add it to the alt attribute?


function addAltAtrr() {
    //get the images
    let grabImage = document.querySelectorAll("img"); 
     
    //loop through all images
    for (let i = 0; i < grabImage.length; i++) {  
        grabImage[i].setAttribute("alt", "test");   
    }

}

addAltAtrr();

This currently adds the string "text" as an alt attribute


Solution

  • You can use the alt and title properties, which reflect the attributes of the same names. This is assuming by "title" you mean the title attribute, which shows as a hover tooltip. If you mean the file name, you could use the image element's src, but you'll probably want to process it, removing the file extension for instance.

    Also note that screen readers may speak both alt and title, which would be redundant if one is based on the other.

    function addAltAttrs() {
        //get the images
        let images = document.querySelectorAll("img"); 
         
        //loop through all images
        for (let i = 0; i < images.length; i++) {
            //add alt text if missing (but title is present)
            if (images[i].title && !images[i].alt) {
                images[i].alt = images[i].title;
            }
        }
    
    }
    
    addAltAttrs();