Home > Net >  How do I filter an array by display type if display type is set by bootstrap?
How do I filter an array by display type if display type is set by bootstrap?

Time:02-15

I am trying to filter an array of portfolio cards so that I can see which items are displayed or not.

let pfCard = document.getElementsByClassName("PortfolioCard")

const visibleCards = [...document.getElementsByClassName("PortfolioCard")].filter(x => x.style.display != "none");
console.log(visibleCards.length);

The displayed cards are having the display set to none by a bootstrap class when the media query is met. The code I have been trying to run still grabs all the elements in the array no matter the display type. There are 8 elements in the array and 2 are set to display: none; currently.

CodePudding user response:

Because the element's display property is set by the CSS file, you'll need to get the computed style using window.getComputedStyle:

let pfCard = document.getElementsByClassName("PortfolioCard")

const visibleCards = [...document.getElementsByClassName("PortfolioCard")].filter((x) => {
  return window.getComputedStyle(x).display != "none"
});
console.log(visibleCards.length);
.PortfolioCard {
  width: 100px;
  height: 100px;
  background: red;
  margin: 10px;
}

.PortfolioCard:nth-child(3) {
  display: none;
}
<div ></div>
<div ></div>
<div ></div>

  • Related