Home > Software design >  Filtering products in JavaScript
Filtering products in JavaScript

Time:08-10

so I am trying to filter products when clicking a button, there is an existing class "product-card--hide" that has javascript to hide the products when they have the class. All the products have the class all and then some have other classes depending on their characteristics, so I want to filter based on those classes. I have created this function:

    function filterdeposit(){
        const products = document.querySelectorAll('.all');
        if ((!products.classList.contains('.deposit')) && (!products.classList.contains('.product-card--hide'))){
            products.addClass('.product-card--hide');
        } else if (products.classList.contains('.deposit') && products.classList.contains('.product-card--hide')){
            products.removeClass('.product-card--hide') ;
        } else {
           products = products;
        }
    }

and then I have products and buttons similar to this:

<body>
<button  onclick = "filterdeposit()"> Deposit</button>

<div class= "all deposit";>Deposit</div>
<div class= "all something";>Deposit</div>
<div class= "all somethingelse";>Deposit</div>

</body>

Obviously this example is just to filter for the deposit class but will have separate functions for each of the other products. Here when clicking deposit button it must select all products with class '.all' and then check which of those also have the '.deposit' class and '.product-card__hide' class and remove '.product-card__hide' class if that is true but if they dont contain 'deposit' or 'product-card__hide' then it must add it so the products get hidden. Nothing must happen otherwise (the last else) wasn't sure what to do in that case.

Unfortunately, this isn't working for me, so any advice would be greatly appreciated.

CodePudding user response:

You need to loop through the elements, removing and adding classing as needed, for example by using a forEach, like this:

function filterdeposit() {
  const products = document.querySelectorAll(".all");
  products.forEach((prod) => {
    prod.classList.remove("product-card-hide");
    if (!prod.classList.contains("deposit")) {
      prod.classList.add("product-card-hide");
    }
  });
}
  • Related