Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my JS function only manipulate one <div> that is assigned to the class instead of all?

I have this JS function that is supposed to initially hide a that has the class name "tw" and when clicked on a button it should make it visible. However, whenever I click the button it only changes the visibility of one div. I have 4. How can I fix this?

 function myFunction(){
      var elms = document.getElementsByClassName("tw");
     Array.from(elms).forEach((x) => {
        if (x.style.display === "block") {
          x.style.display = "none";
        } else {
          x.style.display = "block";
        }
      })
    }

https://jsfiddle.net/qm8bxryh/307/
Here’s the fiddle

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I copied your code into the context of a very simple page (see below) and it seems to work…I might have missed something, but could the issue be elsewhere in your project? Perhaps investigating it piece by piece in the browser console could help.

<!DOCTYPE html>
<html>
    <script>
        function myFunction(){
      var elms = document.getElementsByClassName("tw");
     Array.from(elms).forEach((x) => {
        if (x.style.display === "block") {
          x.style.display = "none";
        } else {
          x.style.display = "block";
        }
      })
    }
    </script>
    <body>
        <button onclick="myFunction()">Click me</button>
        <div class="tw">1</div>
        <div class="tw" style="display: block;">2</div>
        <div class="tw">3</div>
        <div class="tw" style="display: block;">4</div>
    </body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading