Is there a way to display: none; all but one element using if statement?

61 Views Asked by At

Trying to hide all but one product card so that the one displayed product card can be turned into a carousel to display the hidden product cards when carousel buttons are clicked.

Product cards will only be hidden when screen size is less that 600px (see media queries)

Javascript

let productIndex = document.getElementsByClassName("product-card")[0];
let productCard = document.getElementsByClassName("product-card");


if (productCard !== productIndex) {
productCard.style.display = "none";
}

The above code block will not hide the product cards but

if (productCard !== productIndex) {
productIndex.style.display = "none";
}

will hide the first the product.

jsfiddle available here

1

There are 1 best solutions below

3
Steph On

In the fiddle, I see 5 product cards. If you just want to hide all but the first one when the screen width is less than 600px, then something like this would work:

window.addEventListener('resize', resize);

function resize() {
  let productCards = document.getElementsByClassName("product-card");
  if (window.innerWidth < 600) {
    for (var i = 1; i < productCards.length; i++) {
      productCards[i].style.display = "none";
    }
  } else {
    for (var i = 1; i < productCards.length; i++) {
      productCards[i].style.display = "inherit";
    }
  }
}

Grab the collection of cards, loop through them starting from the second element, and apply the style depending on the screen width. The event listener makes it responsive.

Edit: There's an even easier approach; instead of using javascript, you can put this inside of your media(max-width: 600px) block:

.product-card:not(:first-child) {
  display: none;
}