I need to call the same function separately on separate HTML elements. Specifically, that of this repo (now archived, or I would ask there). It gathers all of the elements of a class/figure to put them into a single PhotoSwipe gallery, which I need it to do, but I also need to have several separate galleries on the same page, but this library gathers all of the images and puts them all into every gallery. For that same reason I can’t, say, separate the images of each gallery by class and pass all of them in an array, since they all end up together.
The solution I’ve come upon, which does work, is to call the function repeatedly for each gallery’s class, ie:
initPhotoSwipeFromDOM('.images-container01nnb figure');
initPhotoSwipeFromDOM('.images-container02nnc figure');
initPhotoSwipeFromDOM('.images-container03rv figure');
But, n00b though I am, I still see that as ugly, inelegant, repetitive code. As well, I’m unsure from a performance perspective if that is particularly inefficient or shouldn’t be done in that way? Either way, there surely must be a better, cleaner, more elegant way to call that same function separately on distinct HTML classes?
2
Answers
The function uses
document.querySelectorAll()
to get all elements that match the selector, so you can use a comma-separated selector to match them all at once:If you just want to make the code more ‘elegant’, i.e. not repetitive, you could use
[class^="images-container"]
to get all of the image containers, then iterate over the list and call the function, something like:where I have a mock
initPhotoSwipeFromDOM
that just changes the text color to demonstrate.