Webflow sync, pageviews & more.
NEW

Has anyone successfully added a dynamic class name to each item within a Webflow collection list using custom JS? We want to vary the styling across the list items based on a field within the CMS. We're aware of the option to use multiple collection lists for different styling, but we're looking for more control. Any advice or examples would be appreciated. Thank you!

TL;DR
  • Add a hidden element in each CMS item with a data attribute (e.g. data-style) bound to a CMS field.
  • Use JavaScript to read that attribute and apply its value as a class to the corresponding collection item for dynamic styling.

Yes, it's possible to add dynamic class names to each item in a Webflow Collection List using custom JavaScript, based on a CMS field value.

Here’s how to do it step-by-step:

1. Expose the CMS Field as a Data Attribute

  • Inside your Collection List Item, add a Text Block or Embed Element that contains the CMS field you want to use for dynamic classes.
  • Set the element’s custom attribute like:
  • Attribute Name: data-style
  • Attribute Value: {{Custom CMS Field}} (bind the value from your Collection)

For example, for a CMS field called “Style”, it might insert “primary”, “secondary”, “alert”, etc.

  • Optionally, visually hide this element by applying a class with display: none.

2. Write JavaScript to Add the Class

  • Add a custom code block at the end of the page (before </body>) in Page Settings or Site Settings.

  • Use a script like this:

<script>  document.addEventListener("DOMContentLoaded", function() {    var items = document.querySelectorAll('[data-style]');    items.forEach(function(item) {      var className = item.getAttribute('data-style').trim().toLowerCase();      if (className) {        item.closest('.w-dyn-item').classList.add(className);      }    });  });</script>

Key Notes:

  • item.closest('.w-dyn-item') assumes your dynamic list items use Webflow’s standard class.
  • Adjust .w-dyn-item to the actual container you want to target if necessary.
  • Make sure CMS field values are valid class name strings (no spaces or special characters).

3. Style According to Added Classes

  • In Webflow Designer, create classes matching those CMS values (e.g., .primary, .secondary, .alert) and style them accordingly.

Summary

You can apply dynamic class names to Webflow CMS items by exposing a CMS field via a hidden data-* attribute, then using JavaScript to apply that value as a class to the collection item. This gives you flexible styling without duplicating collection lists.

Rate this answer

Other Webflow Questions