Kaio Almeida
Kaio Almeida

Reputation: 59

Javascript does not recognize the same class on another div

I am studying JS, I created this gallery and I am trying to make a modal that takes the selected image. I can only do this in the first div, the others don't work.

Here's my code on CodePen https://codepen.io/KaioRocha/pen/rNNRzEp

    // Get the modal
    var modal = document.getElementById("myModal");

    // Get the image and insert it inside the modal - use its "alt" text as a caption
    var img = document.querySelector(".myImg");
    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;
    }

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

Upvotes: 1

Views: 52

Answers (2)

Mamun
Mamun

Reputation: 68933

querySelector() returns the first element within the document that matches the specified selector, or group of selectors.

You should use querySelectorAll() to target all the images with the specified class, then loop through them to attach the event individually like the following way:

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

Upvotes: 4

fila90
fila90

Reputation: 1459

document.querySelector(".myImg"); will select only the first .myImg. Every other will stay intact.

You can select them all with document.querySelectorAll(".myImg");, then run them trough loop and add event listener on every one of them.

Upvotes: 1

Related Questions