0

I'm trying to create an image sorter with toggle buttons, but my function is only working for the first image with the ID and not any others.

This is the JS function

function kitchen() {
  var x = document.getElementById("kitchen");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

Here is the html button

<button onclick=kitchen()>Kitchen</button>
<img src="https://picsum.photos/200/?" id="kitchen">
<img src="https://picsum.photos/200/?" id="kitchen">

I'm expecting it to toggle display block on all images with the id "kitchen" but it is only doing the first image.

Ben Smallwood
  • 43
  • 1
  • 7
  • Possible duplicate of [Does ID have to be unique in the whole page?](https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page) – Taplar May 20 '19 at 21:17
  • Also `document.getElementById` only returns a single element. As reinforced by the **getElement** part of the method name – Taplar May 20 '19 at 21:18
  • @Taplar then how should I get around this. make it a class? – Ben Smallwood May 20 '19 at 21:18
  • `getElementById` returns a single (first) element. Meanwhile `id` must be unique. Use `class="kitchen"` and `getElementsByClassName`. – Alex Kudryashev May 20 '19 at 21:19
  • @AlexKudryashev hey Alex, I tried that but now it doesn't show any images onclick – Ben Smallwood May 20 '19 at 21:22

1 Answers1

1

It should be something like this.

function kitchen() {
  var imgs = document.getElementsByClassName("kitchen");
  for (var i = 0, img; img = imgs[i]; ++i) {
    img.style.display = img.style.display == 'none' ? 'block' : 'none';
  }
}
<button onclick="kitchen()">Kitchen</button>
<img style="display:none" src="https://picsum.photos/200/?" class="kitchen">
<img src="https://picsum.photos/200/?1" class="kitchen">
Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36