Marius Vasile

Marius Vasile

  • 585
  • 1.9k
  • 149.3k

show hide divs on button click with javascript

Feb 8 2023 7:08 PM

I am trying to show/hide divs with button click. I couldn't find something that works. I know how to do it with jquery but I have to use javascript for this one. What I tried is below

<div class="row">
        <button class="btn col-2 text-danger">Protectia capului</button>
        <button class="btn col-2 text-danger">Protectia mainilor</button>
        <button class="btn col-2 text-danger">Protectia fetei</button>
        <button class="btn col-2 text-danger">Protectia picioarelor</button>
        <button class="btn col-2 text-danger">Protectia corpului</button>
        <button class="btn col-2 text-danger">Protectia respiratorie</button>
        <button class="btn col-2 text-danger">Protectia electrica</button>
    </div>
</header>
<div class="div">Section 1</div>
<div class="div">Section 2</div>
<div class="div">Section 3</div>
<div class="div">Section 4</div>
<div class="div">Section 5</div>
<div class="div">Section 6</div>
<div class="div">Section 7</div>
<script>
    var buttons = document.querySelectorAll('.btn');
    var divs = document.querySelectorAll('.div');

    for (var i = 1; i < buttons.length; i++) {
        buttons[i].onclick = function() {
            
            if (divs[i].style.display === "none") {
                divs[i].style.display = "block";
            } else {
                divs[i].style.display = "none";
            }
        };
    }
</script>

 


Answers (6)