Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!