-3

How to change an image src according to it's unique alt attribute by using a for loop targeted by document.querySelectorAll(img) using vanilla JS. Ty

This

<img src="../../img/potatoes.png" alt="potatoes">

Into

<img src="../../img/potatoes/newpotatoes.png" alt="potatoes">

0

1 Answer 1

2

You can use array filter to get specific elements

[].slice.call(document.querySelectorAll('img')).filter(function(img){
    return img.alt === 'potatoes';
}).forEach(function(img){
  img.src = img.src.replace('.png', '/new' + img.alt.charAt(0).toUpperCase() + img.alt.slice(1) + '.png')
});
2
  • Awesome, will that work to target the specific "potatoes" alt tag or it will change all img tag sources into newPotatoes? If I have multiple images with different alt tags how can I specify only the one with the unique alt tag potatoes? Ty for your time and apologies for so many potatoes.
    – Monolithic
    Jul 20, 2016 at 20:13
  • I have edited my answer, it will work with any number of images, if any of the img alt tag is 'potatoes' it will be replaced.
    – cstuncsik
    Jul 21, 2016 at 3:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.