Monolithic Monolithic - 4 months ago 15
Javascript Question

Change <img> src according to it's alt attribute

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">

Answer
[].slice.call(document.querySelectorAll('img')).forEach(function(img){
  img.src = img.src.replace('.png', '/new' + img.alt.charAt(0).toUpperCase() + img.alt.slice(1) + '.png')
});