Uncaught TypeError: Cannot read properties of undefined (reading 'src') when trying to change image src to another image source through for loop

Viewed 10

i have js function that change my product main image src to another image src ,the function work normal but when i put it inside for loop it give me undefined error.

this is the working code:

  var mainImg=document.querySelector(".single-prod-img .mainImg");
  var smallImg=document.querySelectorAll(".small-img-group .small-img")


 smallImg[0].onclick = function(){
   mainImg.src=smallImg[0].src;
 }
 smallImg[1].onclick = function(){
   mainImg.src=smallImg[1].src;
 }
 smallImg[2].onclick = function(){
   mainImg.src=smallImg[2].src;
 }
 smallImg[3].onclick = function(){
   mainImg.src=smallImg[3].src;
 }

this is the code that give me the error

  var mainImg=document.querySelector(".single-prod-img .mainImg");
  var smallImg=document.querySelectorAll(".small-img-group .small-img")

  for(var i=0;i<smallImg.length;i++){
     smallImg[i].onclick = function(){
    mainImg.src=smallImg[i].src;
  }
}
0 Answers
Related