How to implement conditional visibility to Webflow CMS based off of the number of collection items?

Does anyone know if you can use conditional visibility in the Webflow CMS to completely hide a collection list based off of the number of collection items in a specific category, or if there is a code solution for this?

Here’s some context:

You have a Project page showing “Similar projects” at the bottom. The “Similar projects” at the bottom share the same category. In the event that there are not THREE projects in a specific category, the entire collection list for the “Similar projects” section will be hidden.

Not possible with Webflow’ conditional logic but you can use custom code to do this. You would look at the length of the array of elements then have a conditional to hide the group if it is less than X.

1 Like

Any chance you could provide an example of the code for this?

Let’s assume your collection list wrapper, or a DIV containing it, has the unique ID dynListArea. You want the whole thing to appear only if there are 3 collection list items, and to disappear of there are more, or less than that.

Add this custom code to your page or site /head area.
You can add it to an HTML Embed if you want it to take effect in the designer as well.

<style>
#dynListArea:not(:has(.w-dyn-item:nth-last-child(3):first-child)) {
  display: none;   
}
</style>

Here are 4 related CSS selector patterns you might find useful;

An important caveat with the pseudo-class has: is that the global coverage of support in browsers is only about 80% and currently zero in Firefox. So you might want to factor that into whether this should be handled with JavaScript or CSS. While not: is considerably better. A reason I am not currently this approach on client sites.

If coverage is a non issue then this is a easy approach!

See "has:" | Can I use... Support tables for HTML5, CSS3, etc

1 Like

Kudos, Jeff, that’s a very important caveat.

I had a similar problem, but in addition to hiding CMS collection, I wanted to hide the whole section containing that CMS collection.

Here’s the JS that worked for me:

<style>
  .hidden {
    display: none;
  }
</style>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    const sectionHomeEvents = document.querySelector("#section_home-events");
    const dynItems = sectionHomeEvents.querySelectorAll(".w-dyn-item");

    if (dynItems.length === 0) {
      sectionHomeEvents.classList.add("hidden");
    }
  });
</script>

This script targets the div with the id “section_home-events” and adds the .hidden class to it if there are no child elements with the .w-dyn-item class. This will effectively hide the div if it doesn’t contain any elements of the specified class.

Thanks Patryk, works like a champ.

1 Like