Webflow sync, pageviews & more.
NEW

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 an empty state to your CMS Collection and assign custom attributes (e.g., data-empty-parent, data-empty-child) to the parent and child elements.
  • Use JavaScript placed before the tag to detect if the empty child is visible and hide the parent container accordingly.

Yes, you can write custom JavaScript in Webflow to hide a parent div when a child element is visible (e.g., set to display: block), typically to account for empty CMS Collections.

Here’s how to do it:

1. Identify the Empty State Element

  • Webflow adds a specific structure when a CMS Collection is empty.
  • The "Empty State" element is a child div that appears when the collection has no items.
  • Ensure you’ve added this in the CMS Collection List → go to the Settings panel → click “Add Empty State”.

2. Add Custom Attributes for Targeting

  • Assign a unique combo class or custom attribute to:
  • The parent container that wraps your CMS Collection (e.g., data-empty-parent)
  • The empty state child element (e.g., data-empty-child)

3. Add Custom JavaScript to Hide the Parent

  • Inside Page Settings > Before tag, paste the following logic (rewritten to follow Webflow safe use):

Use this inline logic:

  • Look for the empty state child that is display: block
  • If found, hide the parent container

Example:

<script>  document.addEventListener("DOMContentLoaded", function () {    var emptyChild = document.querySelector('[data-empty-child]');    var parentContainer = document.querySelector('[data-empty-parent]');        if (emptyChild && parentContainer) {      var isVisible = window.getComputedStyle(emptyChild).display === "block";      if (isVisible) {        parentContainer.style.display = "none";      }    }  });</script>

4. Important Notes

  • Display fallback: If you're using display: flex or grid in the empty child, adjust the condition accordingly.
  • Multiple Collections: If using multiple empty states on the same page, you'll need to loop through each set of parent/child nodes.
  • jQuery Alternative: You can use jQuery if you’ve loaded it, but the vanilla method above is preferred for performance.

Summary

To hide a parent element when a Webflow CMS Collection is empty, use JavaScript to detect the empty state child element's visibility and then hide the parent accordingly. Tag elements with custom attributes or classes for specificity and apply the script at the end of the page body.

Rate this answer

Other Webflow Questions