javascriptimagefor-loopdomimage-enlarge

How to loop through getElementsByClass for image expansion


The for loop is not working to expand the image.

When I place an index at the end, it works. So I know indirectly that there is nothing wrong with HTML and CSS, and that the function works.

const expandImage = document.getElementsByClassName('website_image')[0];

expandImage.addEventListener('mouseover', expand);

function expand(event){
  expandImage.style.padding='11%';
}

However, when I attempt to do a for loop:

const expandImage = document.getElementsByClassName('website_image');

for(let i=0; i<expandImage.length; i++) {

expandImage.addEventListener('mouseover', expand);

function expand(event){
  expandImage.style.padding='11%';
}
}

Nothing happens.

What am I doing wrong?


Solution

  • You're not referencing the array element in your loop, you're referencing the whole array. You need to use the equivalent of [0] inside your loop, in this case, [i].

    const expandImage = document.getElementsByClassName('website_image');
    
    for(let i=0; i<expandImage.length; i++) {
    
    expandImage[i].addEventListener('mouseover', expand);
    
    function expand(event){
      expandImage[i].style.padding='11%';
    }
    }
    

    But you'll find this won't work either! You can't access expandImage[i] within your function because by the time it executes, i is equal to expandImage.length. You'll need to store a reference in the declaring scope for the current element of expandImage, or it might be simpler to just use the this object in your method:

    const expandImage = document.getElementsByClassName('website_image');
    
    for(let i=0; i<expandImage.length; i++) {
    
    expandImage[i].addEventListener('mouseover', expand);
    
    function expand(event){
      this.style.padding='11%';
    }
    }