Loop to change all alt="" values in a document

Viewed 44

I am trying to change all alt="" values in a document.

I have different divs: in this example div.product-card, which includes div.product-details and div.product tumb.

var change = document.querySelectorAll('div.product-card').forEach(function(){
    var imagename = document.querySelector('div.product-details h2 a').text;
    var image = document.querySelector("div.product-tumb div img");
    image.setAttribute("alt", imagename);
})

This code runs but it only changes the first occurrence.

But I need to make a loop of all .product-cards, find the imagename in each product-detail and set accordingly the alt value in each .product-tumb.

1 Answers

You should use the current element in the loop. Also you should use innerText or textContent to get the element's text:

var change = document.querySelectorAll('div.product-card').forEach(function(el){
  var imagename = el.querySelector('div.product-details h2 a').textContent;
  var image = el.querySelector("div.product-tumb div img");
  image.setAttribute("alt", imagename);
})
Related