简体   繁体   English

为所有图像添加 Alt 属性 - Vanilla Javascript

[英]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?我如何能够遍历所有图像,检索图像标题,然后将其添加到 alt 属性?


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这当前将字符串“text”添加为 alt 属性

You can use the alt and title properties, which reflect the attributes of the same names.您可以使用alttitle属性,它们反映了相同名称的属性。 This is assuming by "title" you mean the title attribute, which shows as a hover tooltip.这是假设“标题”是指title属性,它显示为 hover 工具提示。 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.如果您指的是文件名,则可以使用图像元素的src ,但您可能想要处理它,例如删除文件扩展名。

Also note that screen readers may speak both alt and title , which would be redundant if one is based on the other.另请注意,屏幕阅读器可能会说alttitle ,如果一个基于另一个,这将是多余的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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