'Show/hide div in JS

I'm pretty fresh to JS.

For n amount of bar divs I have n amount foo divs. By clicking on bar[1], I want foo[1] to show or hide. The same goes for bar[2]/foo[2], bar[5]/foo[5], bar[3]/foo[3],...bar[n]/foo[n] in no exact order.

With this code I am able to show and hide, but only all of the divs at the same time. What should I change, so that I am able to hide or show only one of the divs?

function getContent() {
  var x = document.getElementsByClassName("foo");
  for (var i = 0; i < x.length; i++) {
    if (x[i].style.display === "none") {
      x[i].style.display = "block";
    } else {
      x[i].style.display = "none";
    }
  }
}

document.querySelector(".bar").addEventListener("click", getContent);
.foo {
  display: none;
}

.bar {
  padding: 5px;
  display: block;
}
<div>
     <div class="bar" onclick="getContent()">bar</div>
</div>
<div class="foo">foo</div>


Solution 1:[1]

No need to use JS here, HTML is more powerful than you think: if you want to show-or-hide information, the <details> element's got you covered.

.all-or-nothing summary {
  display: inline-block;
  cursor: pointer;
}
<details class="all-or-nothing">
  <summary>Toggle all divs</summary>
  <div>
    The first div
  </div>
  <div>
    The second div
  </div>
    <div>
    The third div
  </div>
</details>

Solution 2:[2]

Use a variable to hold the index of the current DIV to show, rather than looping over all the DIVs.

let fooIndex = 0;
let allFoo = document.querySelectorAll(".foo");

function getContent() {
  if (fooIndex < allFoo.length) {
    allFoo[fooIndex].classList.toggle("foo");
    allFoo[fooIndex].classList.toggle("bar");
    fooIndex++;
  }
}

document.querySelector(".bar").addEventListener("click", getContent);
.foo {
  display: none;
}

.bar {
  padding: 5px;
  display: block;
}
<div>
  <div class="bar">bar</div>
</div>
<div class="foo">foo1</div>
<div class="foo">foo2</div>
<div class="foo">foo3</div>
<div class="foo">foo4</div>

Solution 3:[3]

//let fooIndex = 0;

function getContent() {
    var x = $(".card");
    x.append('<div class="foo" onclick="hideContent(this)">foo1</div>');
    //$(this).addClass('bar');
  }

   function hideContent(a) {
    $(a).removeClass('foo');
    $(a).addClass('bar');
  }
.foo {
  display: none;
}

.bar {
  padding: 5px;
  display: block;
}
<div class="card">
  <div onclick="getContent();" class="bar">bar</div>
</div>

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 Mike 'Pomax' Kamermans
Solution 2 Barmar
Solution 3