I'm trying to build a set of filters using checkboxes.
For example, I have:
- Red squares
- Red circles
- Blue squares
- Blue circles
and want to be able to filter based on the color AND the shape. I'm having difficulty.
If you run the code in this post, you'll see that my .querySelector() method is not pulling in all the elements with the '.red' class. It's only altering the first element with that class name, not every element with the class name. If I use the .querySelectorAll() method I also have no luck.
My desired outcome is checkboxes that are "red only", "blue only", "circles only", and "squares only" and that can have MORE THAN ONE filter active at a time.
Any help is appreciated.
const allRedItems = document.querySelector(".red");
const checkBox = document.querySelector('#hide');
checkBox.addEventListener('change', function(e){
if (hide.checked){allRedItems.style.display = "none";}
else { allRedItems.style.display = "inline-block"; }
});
div {
height:100px;
width:100px;
border:1px solid #ccc;
display:inline-block;
margin:2rem;
}
.red {
background-color:red;
}
.blue {
background-color:blue;
}
.square {
border-radius:5px;
}
.circle {
border-radius:50%;
}
<div class="red circle"></div>
<div class="red square"></div>
<div class="blue circle"></div>
<div class="blue square"></div>
<br>
<input type="checkbox" id="hide">
<label for="hide">Hide All Red Elements</label>