How can I read specific data from a Webflow collection item using custom code in JavaScript, when there are multiple rows with repeated buttons on the page?

TL;DR
  • Add custom data- attributes in Webflow to expose Collection field values (e.g., data-item-id) on each Collection item.  
  • Attach click event listeners to buttons; on click, use .closest('.w-dyn-item') to find the related Collection item and read its data- attributes or nested element content.

To read specific data from a Webflow Collection item using JavaScript when you have repeated buttons (e.g., one per Collection list item), you need to structure your HTML with clear data attributes and identify the correct item context on button click.

1. Add Data Attributes in Webflow

  • In the Webflow Designer, select the Collection List item or elements inside it (like a button or wrapper div).
  • Add custom attributes to elements using the Element Settings panel (gear icon).
  • Example: add a custom attribute like data-item-id and bind it to a Collection field (e.g., Slug or ID) using Add field.

2. Set Up Button Click Handling in JavaScript

  • Use event delegation or loop through the buttons so each button's click reads data from its corresponding Collection Item.
  • Example: give each button a class like .read-btn, then add a click listener.

3. Read Data Relative to the Clicked Button

  • On click, target the closest Collection Item wrapper (e.g., .w-dyn-item) and read data attributes or child text.

const buttons = document.querySelectorAll('.read-btn');

buttons.forEach((btn) => {
  btn.addEventListener('click', function () {
    const item = this.closest('.w-dyn-item');

    // Example: read a bound data attribute
    const itemId = item.getAttribute('data-item-id');

    // Or read text from a nested element
    const title = item.querySelector('.item-title')?.textContent;

    console.log('Item ID:', itemId);
    console.log('Title:', title);
  });
});

  • .w-dyn-item is the standard Webflow class for a Collection Item — ensure you’re selecting from the correct context.

4. Optional: Use data- Attributes for Multiple Fields

  • To avoid traversing the DOM, bind multiple Collection fields as data- attributes at the top level .w-dyn-item.
  • Example: data-titledata-iddata-url

Summary

To read data from a Webflow Collection item via JavaScript:

  • Use data attributes in the Designer to expose Collection field values.
  • Attach event listeners to each button.
  • On click, use .closest('.w-dyn-item') to find the item context and read data attributes or child content accordingly.
Rate this answer

Other Webflow Questions