The collection-filter element

Overview

The <collection-filter> element is a utility to simplify collecting a query from a user, and then using that query to filter an arbitrary collection of elements.

The element provides a text query along with a regex indicator, to toggle regex matching on the collection items. It is meant to be used like a "search bar".

Basic Example

The <collection-filter> element prepares a query from user input and provides that query on the change event's detail property.

In the example below, the change event is handled with a custom function that does the following:

  • Detects if the query is empty and, if so, clears all matching elements.
  • Uses the filterElements method to find all of the elements in the example whose text content matches the query.
  • Adds or removes a match class to each example element, depending upon whether they match the query or not.

Try searching for "A", then "B", and then "F" to see the different collections that are selected, based on the text content.

Note how matches can occur anywhere within the text, instead of requring an exact text match. In the case that exact text matches are expected, use the regex toggle to perform a Regular Expressions text search.

A
B
C
D
E
F
Far
Fear
Big
Dandy

Custom Filter Property Value

The <collection-filter> element is not limited to searching for the text content of the elements it filters. The data-filter-property attribute can be used to provide a key for matching on.

In this example, the "E" element has been given the data-filter-property attribute of "a" so that it won't match on "E", but will match on "A", along with the rest of the eleemnts that match the "A" query:

A
B
C
D
E
F
Far
Fear
Big
Dandy

Custom Filter Property

The <collection-filter> element's filter-property attribute allows customization of the attribute that is used for matching items.

Whatever value is provided to the filter-property attribute will be the attribute name that the filterElements() method will will match on.

In this example, the filter-property is set to data-name, and each item has a data-name attribute with a value for matching. The attributes are keyed "a" through "j", and they all also have a key of "name".

Note how the "Far" and "Fear" examples are not matched when searching "F", but every element is matched when searching for "n", "a", "m", or "e":

A
B
C
D
E
F
Far
Fear
Big
Dandy

Events

The <collection-filter> element dispatches a change event whenever a query is submitted by a user, or whenever the query's input changes to an empty value.

In the following example, each change event has its detail property logged in the event log, and the matching results from the filterElements() method logged in the matches log:

A
B
C
D
E
F
Far
Fear
Big
Dandy
OOOO
Event Log
    Matches Log