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 custom attribute (e.g., data-style-class) to each CMS item using a dynamic CMS field value.
  • Use JavaScript to read the attribute and apply it as a class to each item, formatting it to match CSS naming conventions.
  • Define matching CSS classes in Webflow Designer or with embedded styles to control the appearance per class.

You can dynamically add class names to Webflow CMS collection items using custom JavaScript by leveraging a CMS field value as the class modifier. This allows for styling variants without duplicating collection lists.

1. Set Up a Custom Attribute as a Hook

  • In your Collection List, add a custom attribute to an HTML element inside each item (like a div wrapper).
  • Use something like:
  • Name: data-style-class
  • Value: Use the desired CMS field (e.g., collection-field), pulled in dynamically.
  • Example: data-style-class = [Color Variant]
  • If you're using a CMS field called style-type with values like red, blue, green, this stores them per item.

2. Use JavaScript to Apply the Dynamic Class

  • Place this in an Embed element inside the page or in the Before section of Page Settings.
  • The script should query all relevant items, read their data-style-class, and attach it as a class.
<script>  document.addEventListener("DOMContentLoaded", function() {    const items = document.querySelectorAll("[data-style-class]");    items.forEach(function(item) {      const style = item.getAttribute("data-style-class");      if (style) {        item.classList.add(style.trim().toLowerCase().replace(/\s+/g, '-'));      }    });  });</script>
  • This makes a CMS value like "Primary Blue" become the class "primary-blue" on that element.
  • Make sure to use a consistent class name format in your CSS or Webflow Designer (e.g., define .primary-blue, .red, etc.).

3. Create Corresponding CSS Styles Inside Webflow

  • Either in Webflow Designer, create utility classes with custom styles (e.g., .red-bg, .green-text),
  • Or, embed custom <style> tags via an Embed block and define CSS rules directly.

Summary

By passing CMS field values via data-* attributes and applying them with custom JS, you can dynamically assign class names to each item in a collection list. This approach delivers full styling flexibility across list items without needing multiple Collection Lists or static class lists.

Rate this answer

Other Webflow Questions