0

I am wanting to hide all elements with the id=showhide

So I set my javascript as

<script type="text/javascript">

    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
</script>
</body>

and then my button as

<a href="#" onclick="toggle_visibility('showhide');">
                            <button>Show / Hide Details</button>
                            </a>

then I went and added the ID to a table, but it's only hiding the first instance of this ID, not all?

Cleptus
  • 3,446
  • 4
  • 28
  • 34
Henry Aspden
  • 1,863
  • 3
  • 23
  • 45
  • 8
    `id` are meant to be unique, instead use `class` for more than 1 element. – Nikhil Aggarwal Jun 26 '19 at 16:59
  • 3
    Buttons can't be descendants of links – j08691 Jun 26 '19 at 17:00
  • For the time after the switch to `class` [javascript - What do querySelectorAll and getElementsBy* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Andreas Jun 26 '19 at 17:00

2 Answers2

3

Like others have mentioned, you need to use a class instead of id. getElementById returns only one element while getElementsByClassName will return a collection of all elements (NodeList) with that class. I've attached a snippet showcasing how the code could look.

function toggle_visibility(className) {
  const elements = document.getElementsByClassName(className);
  for (const e of elements) {
    e.style.display = e.style.display === 'none' ? 'block' : 'none';
  }
}
<button onclick="toggle_visibility('showhide');">
  Show / Hide Details
</button>

<div class="showhide">A</div>
<div class="showhide">B</div>
<div class="showhide">C</div>
Dehli
  • 5,950
  • 5
  • 29
  • 44
0

You can not use id for this purposes. ID by it's ideology must be the SINGLUAR in your html. You can for instance use classes and document.getElementsByClassName Or you can use some specific attributes, whatever more convinient for you except ID's.

Viktor
  • 188
  • 7