user3200582
user3200582

Reputation: 43

Toggle-Button hide other elements by class

I am trying to achieve a filter that hides other divs by their class name. So far I have the following code, which unfortunately doesn't work. Please help me out, THX!!!

<button id="toggle">Toggle</button>
<div class="text to-filter">Lorem ipsum dolor sit amet.</div>
<div class="text not-to-filter">Lorem ipsum dolor sit amet.</div>

<script>
 var button = document.getElementById('toggle'),
 text = Array.document.getElementsByClassName("text");
 button.onclick = function() {
   var isHidden = texts.style.display == 'none';
   text.forEach(function(){
    style.display = isHidden ? 'block' : 'none';
   });
 };
</script>

Upvotes: 1

Views: 150

Answers (2)

Chi Row
Chi Row

Reputation: 1106

Here is a javascript version.

Add an 'onclick=toggleDiv()' attribute to the button and then,

function toggleDiv() {
    var text = document.getElementsByClassName("text");
    for (var i = 0; i < text.length; i++) {
        var status = text[i].style.display;
        text[i].style.display = (status=="" || status=="block") ? "none":"block";
    };
}

On click of the button, all 'text' class div will toggle on or off.

Upvotes: 1

CRABOLO
CRABOLO

Reputation: 8793

The following code will hide any elements that have the class .to-filter when the user clicks on #toggle the first time. When they click on it again it will show the elements again.

$('#toggle').on('click', function() {
    $('.to-filter').toggle();
});

Upvotes: 0

Related Questions