javascriptalt-attribute

How to add alt text to images without an ID


I need to add alt text to various images which do not have IDs or anything else to identify the images from one another other there the image file names.

Is there a way to add alt text to each image based on what the image file name is?

Here's an example of the code I started working on, but it obviously doesn't work and I'm not even sure I am heading in the right direct. Any help would be much appreciated.

<script>
document.onload = function(){
  img.setAttribute('src', 'icons-vegan.png');
  img.setAttribute('alt', 'Vegan Icon');
  img.setAttribute('title', 'Vegan Icon'); 
}   
document.onload = function(){
  img.setAttribute('src', 'icons-gluten.png');
  img.setAttribute('alt', 'Gluten Icon');
  img.setAttribute('title', 'Gluten Icon'); 
}   
</script>

Solution

  • We can simply select all the img tags from our HTML and update the alt and title dynamically.

    // find all img tags and convert the list to an array
    const imgs = Array.from(document.getElementsByTagName("img"))
    
    // loop through each image and process the `src` attribute
    imgs.forEach(img => {
      const altText = img.src
        .split("/") // split the string into segments delimited by "/"
        .at(-1) // get last segment
        .split(".").slice(0, -1).join(".") // remove file extension
        // remove dashes and capitalize
        .split("-").map(s => s[0].toUpperCase() + s.slice(1).toLowerCase()).join(" ")
    
      // add properties
      img.setAttribute("alt", altText)
      img.setAttribute("title", altText)
    })
    

    Demo:

    // find all img tags
    const imgs = document.getElementsByTagName("img")
    
    console.log("before adding alt:", [...imgs])
    
    // loop through each image and process the `src` attribute
    Array.from(imgs).forEach(img => {
      const altText = img.src
        .split("/") // split the string into segments delimited by "/"
        .at(-1) // get last segment
        .split(".").slice(0, -1).join(".") // remove file extension
        // remove dashes and capitalize
        .split("-").map(s => s[0].toUpperCase() + s.slice(1).toLowerCase()).join(" ")
    
      // add properties
      img.setAttribute("alt", altText)
      img.setAttribute("title", altText)
    })
    
    console.log("after adding alt:", [...imgs])
    <img src="icons-vegan.png" />
    <img src="icons-gluten.png" />
    <div>
      <img src="/something/something-else.png?12345" />
    </div>