my javascript queryselectorall does not capture the second class name as intended

66 Views Asked by At

I have two images with different classes but I want the same JavaScript to be applied to both. This javascript basically allows for a slideshow by clicking on the button, but this only works for the images with the mySlides class, not the albums class. Take a look:

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.querySelectorAll(".mySlides, .albums");
  if (n > x.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = x.length
  };
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex - 1].style.display = "block";
}
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>
<div class="inner">
  <img class="mySlides" src="./imgs/IMG_1552.JPG">
  <img class="mySlides" src="./imgs/IMG_0915.jpg">
  <button class="w3-button w3-display-left" onclick="plusDivs(-1)">&#10094;</button>
  <button class="w3-button w3-display-right" onclick="plusDivs(+1)">&#10095;</button>
</div>

<div class="inner">
  <img class="albums" src="./imgs/travis.jpg">
  <img class="albums" src="./imgs/killy.jpg">
  <button class="w3-button w3-display-left" onclick="plusDivs(-1)">&#10094;</button>
  <button class="w3-button w3-display-right" onclick="plusDivs(+1)">&#10095;</button>
</div>

The buttons are supposed to move to the next image eg from "travis.jpg" to "killy.jpg" but it only works for the mySlides class and not the albums class

1

There are 1 best solutions below

1
On

The issue lies in var x = document.querySelectorAll(".mySlides, .albums"); As you have to understand that this query selects all the 4 elements if you want to do for the second element of both classes you would have to go with

var x = document.querySelectorAll(".mySlides");
var y = document.querySelectorAll(" .albums");

and run the further logic on both var seperately