How can I count the number of images in each item of a collection in Webflow and display it in a text block?

Published on
September 22, 2023

To count the number of images in each item of a collection in Webflow and display it in a text block, you can utilize a combination of custom code and conditional visibility settings. Follow the steps below to achieve this:

  1. Create a new text block where you want the image count to be displayed. Give it a unique class name that you can use to target it later.
  2. Open the Collection Template page for the collection you want to count the images in.
  3. Select the first collection item on the page and give it a unique class name.
  4. Open the Settings panel for the collection item and go to the Custom Code section.
  5. In the Before <body> tag field, paste the following code snippet:
<script>document.addEventListener('DOMContentLoaded', () => {  const imageCount = document.querySelectorAll('.unique-class-name img').length;  document.querySelector('.text-block-class-name').innerText = imageCount;});</script>

Replace .unique-class-name with the class name you gave to the collection item in step 3, and replace .text-block-class-name with the class name you gave to the text block in step 1.

  1. Save and publish your site to see the image count dynamically generated for each collection item.

By using the above method, you can count the number of images within each collection item and display it in a text block on the Collection Template page for that particular collection.

Search Engine Optimization (SEO) tip:
To optimize your Webflow site for search engines, make sure to include relevant keywords in the text block where you display the image count. This will help search engines understand the context of your page and improve its visibility in search results.

Example:

<script>document.addEventListener('DOMContentLoaded', () => {  const imageCount = document.querySelectorAll('.collection-item img').length;  document.querySelector('.image-count').innerText = imageCount;});</script><p class="image-count">0</p>

Additional questions:

  1. How do I loop through a collection list in Webflow?
  2. Can I add dynamic content to my Webflow site?
  3. How can I use conditional visibility in Webflow?