Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

73
Views
Can't get getElementsByClassName or querySelectorAll to work

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';

  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!