0

So i wrote a fairly simple function to remove the "hidden" class from 3 items, when another element is clicked. Onclick it gets the 3 items right but it only changes item1+3 and item2 needs another click. I have absolutly no clue why this is happening.

https://codepen.io/zafire/pen/ExexWre

function lmao() {
  const collection = document.getElementsByClassName("hidden");
  console.log(collection.length);
  for (var i = 0; i < collection.length; i++) {
    collection[i].classList.remove("hidden");
  }
}
body {
  text-align: center;
  font-size: 27px;
}

.hidden {
  display: none;
}

.nothidden {
  display: block;
}
<div>
  <span onclick="lmao()">arrow</span>
  <br><br><br>
  <span class="hidden">item1</span>
  <br>
  <span class="hidden">item2</span>
  <br>
  <span class="hidden">item3</span>
  <br>
</div>

Also i would like to notice solved this now differently but im still curious why this particular code does not work.

  • 1
    Take a look at [this answer](https://stackoverflow.com/a/66480319/16688813). – Tom Feb 14 '23 at 13:10
  • Also instead of classes showing and hiding give them `class="menuItem" hidden` and use `window.addEventListener("DOMContentLoaded", () => { const menuItems = document.querySelectorAll(".menuItem"); const toggle = show => menuItems.forEach(item => item.hidden = !show); toggle(1); }) ; ` ` – mplungjan Feb 14 '23 at 13:21

1 Answers1

3

If you read the MDN docs of getElementsByClassName

Warning: This is a live HTMLCollection. Changes in the DOM will reflect in the array as the changes occur. If an element selected by this array no longer qualifies for the selector, it will automatically be removed. Be aware of this for iteration purposes.

So when you remove the class from an element the list is affected.

You can create an array from the initial selection

const collection = [...document.getElementsByClassName("hidden")];

of you can use querySelectorAll

const collection = document.querySelectorAll(".hidden");

which states

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

and now you can iterate over it with no worries.

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317