In my comment I said that this would be a lot shorter if you used JQuery. Now I don't want to say that JQuery is better than plain Javascript. There may be a good reason to not use JQuery. But I do want to show what the code would look like in JQuery.
$(".filter-btn").click(function() {
let type = $(this).data("filter");
let filter = (type == "all") ? "*" : "[data-filterType='"+type+"']";
$(".grid div").hide().filter(filter).show();
});
As you can see, this is a lot less verbose. You can see a live demo here.
I think it goes totoo far to explain this JQuery code in detail. In broad terms it does this:
- Bind an event handler to the "click" JavaScript event of your buttons.
- Extract the filter type from the data attribute of the clicked button.
- Based on that it creates a filter variable that selects the grid items to be shown.
- We firstFirst hide all grid items and then only show those we wantthe filtered ones.
It is the last line that does all the work.
I intentionally didn't change the HTML so this works on the same HTML as you have now.