简体   繁体   中英

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM