Is it possible to write a JavaScript code in Webflow to hide a parent DIV element when a child element is set to Block, specifically when a CMS collection has no items?

TL;DR
  • Add a custom class (e.g., .no-items-message) to the Webflow CMS “No Items” element and to its parent (e.g., .collection-wrapper).  
  • Insert JavaScript in the page or site footer that waits for DOM load, checks if .no-items-message is visible (display: block), and hides the .collection-wrapper if true.

Yes, you can use custom JavaScript in Webflow to detect when a child element is set to display: block (such as when a CMS Collection returns no items) and hide its parent DIV. This is a common use case when working with CMS-driven visibility logic.

1. Understand the Webflow CMS "No Items" Element

  • Webflow automatically includes a “No Items” wrapper inside CMS Collection Lists.
  • This element becomes visible (display: block) when the Collection List has no content.
  • You can give this element a class name, e.g., no-items-message, for targeting via custom code.

2. Add Custom JavaScript in Page Settings or Site-wide

  • Go to Page Settings or Site Settings → Custom Code → Footer section.
  • Paste a script that checks the computed style of the “No Items” element.

3. Sample Script to Hide Parent When No Items

Here's how to do it using JavaScript without any HTML tags:

  • Ensure your no-items-message and parent div have class names.
  • Example: The parent wrapper has class collection-wrapper.

<script>
  document.addEventListener("DOMContentLoaded", function () {
    // Select the element that shows when there are no CMS items
    const noItems = document.querySelector('.no-items-message');
    // Check if it is visible
    if (noItems && window.getComputedStyle(noItems).display === 'block') {
      // Get the parent wrapper and hide it
      const parent = noItems.closest('.collection-wrapper');
      if (parent) {
        parent.style.display = 'none';
      }
    }
  });
</script>

4. Important Considerations

  • Wait for DOM: Use DOMContentLoaded to ensure elements are in place before querying.
  • Check for display === 'block': This confirms the “No Items” element was triggered to show.
  • Scoped Classes: Make sure your class selectors (e.g., .no-items-message) are unique and not reused elsewhere.

Summary

You can hide a parent DIV in Webflow using JavaScript by checking if the “No Items” element inside a CMS Collection is visible (display: block). Use querySelector and getComputedStyle to conditionally hide the parent wrapper based on CMS content state.

Rate this answer

Other Webflow Questions