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 Collection Item bound to a CMS field as a data source for styling.  
  • Use JavaScript to read the hidden value, convert it to a slugified class name, and apply it to the item.  
  • Define CSS rules for each dynamic class to control styling based on CMS content.

Yes, it is absolutely possible to add dynamic class names to items in a Webflow Collection List using custom JavaScript. This allows you to apply styling based on CMS fields without splitting into multiple Collection Lists.

Here’s how to do it:

1. Add a Custom Attribute or Hidden Field to Each Collection Item

  • In your Collection List, insert a Text Block or Span inside each item that will act as a data attribute selector.
  • Bind this element to the CMS field you want to base your class on (e.g., Category, Tag, Status).
  • Give it a class like style-tag and optionally set it to Display: None so it doesn’t show on the page.

2. Use JavaScript to Read the Content and Apply Classes

  • Add a custom script at the bottom of the page (inside an Embed block or in Page Settings > Footer Code).
  • Use JavaScript to loop through the Collection List items, read the value from the hidden field, and assign it as a class name.

Example:

const items = document.querySelectorAll('.w-dyn-item'); // Collection List items
items.forEach(item => {
  const tagEl = item.querySelector('.style-tag');
  if (tagEl) {
    const classKey = tagEl.textContent.toLowerCase().replace(/\s+/g, '-'); // slugify
    item.classList.add(`style-${classKey}`);
  }
});

3. Create CSS Styles Based on the Dynamic Classes

  • In your custom stylesheet or Webflow’s Page > Custom Code, define styles for .style-[value].
  • Example:  

  .style-featured { background-color: gold; }  

  .style-archived { opacity: 0.5; }

4. Avoid Conflicts and Ensure Slug-Friendly Outputs

  • Sanitize your CMS field values to ensure they’re valid CSS class names.
  • Stick to alphanumeric characters, hyphens, and lowercase when converting field values.

Summary

You can dynamically assign class names to Webflow Collection Items by outputting a CMS field as a hidden element, then using JavaScript to read that value and apply a corresponding class. This gives you flexible styling options without duplicating Collection Lists.

Rate this answer

Other Webflow Questions