1

I found this piece of code online to make a modal (popup) with an enlarged picture, when clicking on the thumbnail. The code is shown below and it uses the unique element ID of the thumbnail.

I want to adapt this code so it works for every thumbnail without having to create unique ID's and multiple modals.

Here is the original code using html elements' ID:

var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

I tried to turn this into working with classes. I realised that getElementsByClassName probably contains multiple items and put the into a list, so I added a for-loop:

var imgs = document.getElementsByClassName("tabs-img");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
for (var img in imgs) {
    img.onclick = function(){
        modal.style.display = "block";
        modalImg.src = this.src;
        captionText.innerHTML = this.alt;
    }
}

However, when clicking the thumbnails, nothing happens.

What is wrong with my adaptation?

Rumturf
  • 86
  • 7

1 Answers1

1

The Web API getElementsByClassName returns an HTMLCollection.

But you cannot use a for...in loop to iterate the items of an HTMLCollection, rather, you can use either a regular for or a for...of loop.

An HTMLCollection is not an Array, but is Array-like https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection. It has additional properties and methods that interferes with for...in. See the accepted answer here -> For loop for HTMLCollection elements

Change your loop to for...of which can iterate over array-like objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

for (var img of imgs) {
  img.onclick = function(){
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
  }
}
wlh
  • 3,426
  • 1
  • 16
  • 32
  • Thank you so much. This is exactly what solved my problem. Coming from a Python background, I'm used to using 'in' in for loops :) Thanks again! – Rumturf Jan 18 '20 at 21:10
  • 1
    @Rumturf No problem. You will find lots of 'false friends' in JavaScript, that is, things that appear to work like the same things in other languages due to similar syntax, but have their quirks in JavaScript. I'm going the other direction. I started with JavaScript and am learning other languages, and have these same types of problems often. – wlh Jan 18 '20 at 21:12
  • Thanks for your reply :) Good luck with learning other languages! – Rumturf Jan 18 '20 at 21:16