-5

Here's a fiddle that i (partly) got to work with the queryselector. http://jsfiddle.net/03rc2j91/ It only hides the first element as it should. But i need to hide all the elements with the same class.

I'm working on a project where i need to target the same class to hide all the images within that class.

I tried using querySelectorAll but it didn't work. Same problem with getElementsByClassName()

Queryselector is the only one i got to work but it's not enough to hide just the first element.

Your help would be much appreciated, Thanks!

function toggleBoxVisibility() {

  if (document.querySelector(".check").checked == true) {

    document.querySelector(".box").style.opacity = '0';

  } else {

    document.querySelector(".box").style.opacity = '1';

  }
}
Tazka
  • 1
  • 1
  • 2
    Please read [ask]. Don't make your question dependant on an external link to be understood. Do provide a [mcve] **that demonstrates your problem**. Showing working code doesn't help us understand what your problem is! – Quentin Feb 28 '22 at 15:00
  • The two functions that "don't work" return **lists** of elements, and you have to iterate through those lists to affect each selected element individually. – Pointy Feb 28 '22 at 15:00
  • Instead of using JS to change individual style properties of individual elements, use the [`classList` API](//developer.mozilla.org/docs/Web/API/Element/classList) and toggle the class of the parent element. Then define all your styles in CSS. – Sebastian Simon Feb 28 '22 at 15:20

1 Answers1

0

Document.querySelectorAll() returns a NodeList, which you can think of like an array of elements. In order to hide each of them, you have to iterate through the list and hide each element individually.

Read more about Document.querySelectorAll(): https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

function toggleBoxVisibility() {
  if (document.querySelector(".check").checked) {
    document.querySelectorAll(".box").forEach(box => {
      box.style.opacity = '0';
    });
  } else {
    document.querySelectorAll(".box").forEach(box => {
      box.style.opacity = '1';
    });
  }
}
.box {
  background: lightblue;
  width: 200px;
  height: 200px;
  display: inline-block;
}
<input type="checkbox" class="check" onclick="toggleBoxVisibility()">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
ElectricShadow
  • 683
  • 4
  • 16