title: JavaScript Toggle Display
body: <p>I'm trying to use vanilla JavaScript to toggle <code>display: none</code> and <code>display: block</code> on elements with the same class. It mostly works, but for some reason you need to click the button twice for it to work and it's eating away at me. The code and a link to CodePen is below.</p>
  
  <p>The HTML:</p>
  
  <pre><code>&lt;div class="a"&gt;a&lt;/div&gt;
  &lt;div class="b"&gt;b&lt;/div&gt;
  &lt;div class="c"&gt;c&lt;/div&gt;
  &lt;div class="d"&gt;d&lt;/div&gt;
  
  &lt;button onclick="toggle('a')"&gt;Toggle A&lt;/button&gt;
  &lt;button onclick="toggle('b')"&gt;Toggle B&lt;/button&gt;
  &lt;button onclick="toggle('c')"&gt;Toggle C&lt;/button&gt;
  &lt;button onclick="toggle('d')"&gt;Toggle D&lt;/button&gt;
  </code></pre>
  
  <p>The JS:</p>
  
  <pre><code>function toggle(div) {
    var divs = document.getElementsByClassName(div);
  
      for(var i = 0; i &lt; divs.length; i++) {
        if(divs[i].style.display === "block") {
          divs[i].style.display="none";
        }
        else {
          divs[i].style.display="block";
        }
      }
  
  }
  </code></pre>
  
  <p>The Demo:</p>
  
  <p><a href="http://codepen.io/terf/pen/LjuCh" rel="nofollow">CodePen</a></p>