根据它的alt属性更改<img/> src

时间:2016-07-20 19:48:24

标签: javascript

如何使用vanilla JS使用document.querySelectorAll(img)定位的for循环,根据其唯一的 alt 属性更改图像 src 。 TY

这个

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

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

1 个答案:

答案 0 :(得分:2)

您可以使用array filter获取特定元素

[].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')
});
相关问题