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>
3
Answers
Basic solution making lots of assumptions given the lack of detailed context
Get all images by simply getting a list of all elements of tag ""
For each image, set its alt = its src
We can simply select all the
img
tags from our HTML and update the alt and title dynamically.Demo:
Select all images and loop them to get their
src
attribute. Once you have them, you can set thealt
attribute for each image which is inside that loop. Here is an example: