1

Can someone explain to me how I can use forEach without an error message? I'm programming since 1 month so maybe it's a simple mistake.

------------------------------------------------------------------------------

let galleryImages1 = document.querySelector(".gallery-img");
let getLatestOpenedImg;
let windowWidth1 = window.innerWidth;



if (galleryImages1) {
    galleryImages1.forEach(function (image) {
        image.onclick = function () {

        }
    });
};
Seasus
  • 21
  • 1

4 Answers4

1

The selector querySelector returns only the first element. If you want to return all the elements which match your query use:

let galleryImages1 = document.querySelectorAll(".gallery-img");
vtolentino
  • 754
  • 5
  • 14
0

Simply change

document.querySelector(".gallery-img");

to

document.querySelectorAll(".gallery-img");

as document.querySelector return a single element and you can not use forEach on single element.

Zuckerberg
  • 1,781
  • 2
  • 10
  • 19
0

Try this:

let galleryImages1 = document.getElementsByClassName("gallery-img");

if (galleryImages1) {
  galleryImages1.forEach(image => {
    image.onclick = () => {
      […]
    }
  });
}

Of course, I would use an eventListener to handle an onclick event, but I tried to follow your path.

Federico Moretti
  • 527
  • 1
  • 11
  • 22
-1

Two problems

1 - The return type of document.querySelectorAll is NodeList and not Array which means it does not implement forEach method. Thus you need to use a for loop. A nodelist is not an array and you cannot use forEach

Modern browsers use a polyfill to use a for loop under the hood But its not doesn't work in all javascript Engines

https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach#Polyfill

Typescript will throw an error too if you try and use foreach and will force you to use a for loop

2 - And use document.querySelectorAll and not document.querySelector to get a nodelist

Dave Keane
  • 729
  • 8
  • 19