I’m building a fictional webshop for plants and currently I’m working on filtering them combining different options (light demand, water demand, toxic etc.).
Using a separate JSON file, I’m creating cards based on the data after the JSON file was fetched:
getPlants().then((data) => {
data.forEach((data) => {
plantcards.insertAdjacentHTML(
"afterbegin",
`<article class="plantcard ${getPlantLight(data.Light)} ${getPlantWater(
data.WaterDemand
)}wasser ${getPlantToxic(data.Toxic)}">
<div class="article-wrapper">
<figure>
<img src="../images/plant_types/${data.Image}" alt="${data.Name}" />
</figure>
<div class="article-body">
<h2>${data.Name}</h2>
<h3>${data.NameLatin}</h3>
<p>
Standort: ${getPlantLight(data.Light)}<br/>
Wasserbedarf: ${getPlantWater(data.WaterDemand)}<br/>
Schwierigkeitsgrad: ${getPlantMaintenance(data.Maintenance)}<br/>
Giftig: ${getPlantToxic(data.Toxic)}<br/>
</p>
<a href="#" class="read-more">
Read more <span class="sr-only">about this is some title</span>
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M12.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</a>
</div>
</div>
</article>`
);
});
});
Then I want to select all elements with the class “plantcard” so that I can hide/unhide the filtered options:
let allPlantcards = Array.from(document.querySelectorAll(".plantcard"));
I always get an empty array with a length of 0, I guess because allPlantcards is created before or while the cards are loaded. I googled a lot and I can’t find a solution for this.
I also tried to place let allPlantcards = Array.from(document.querySelectorAll(".plantcard"));
within other functions but then I can’t use them outside of the function, right?