'Why does my script only act on the first element with a particular ID value?

I have a query that produces a number of DIV id="toggle_panel" I know I can effectively change the ID of the DIV dynamically.

Below is the script, straight from w3schools, which works great out of the box...for the first DIV and first DIV only. How do I apply a dynamic variable from the query to my script?

Second question: How do I get it so the DIV are hidden by default?

function myFunction() {
  var x = document.getElementById("toggle_panel");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

Thank you



Solution 1:[1]

For your first question, using a class would be more appropriate to tag a collection similar html elements.

So your divs should look something like this:

<div class="toggle_panel">...</div>
<div class="toggle_panel">...</div>
<div class="toggle_panel">...</div>

You could then use document.getElementsByClassName('toggle_panel') to access them.

Also to hide them by default, you could use css to target your classes as shown below.

.toggle_panel {
   display: none;
}

Solution 2:[2]

As mentioned in the comments, you can only have one instance of an ID. To achieve the result you want you will have to change the <div id="toggle_panel">content</div> to <div class="toggle_panel">content</div>. Then use the following javascript:

function myFunction() {
  var panels = document.getElementsByClassName("toggle_panel");
  for(var i = 0; i < panels.length; i++) {
    var panel = panels[i];   
    if (panel.style.display === "none") {
       panel.style.display = "block";
    } else {
       panel.style.display = "none";
    }
  }

}

Solution 3:[3]

I think you should use querySelectorAll('toggle_panel') and your code will be like this:

Array.from(document.querySelectorAll('toggle_panel')).forEach((element) => {
  element.display = 'none'
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shane Richards
Solution 2 Chiel
Solution 3 Sebastian Simon