Filter Custom Elements

This tutorial uses declarative filtering in a JSON page object to allow a test to get a list of contacts filtered by a search string in the contact's title. This use case builds on the Custom Elements and Filter a List of Elements Using stringContains tutorials.

Click the DOM Tree Viewer. The example-contact-list element contains nested example-contact-tile elements.

This line in the test returns example-contact-tile elements whose title includes VP text.

const vpContactTiles = await contactListRoot.getContactTilesWithText('VP');

The example-contact-list JSON page object defines a contactTilesWithText element that filters the example-contact-tile elements by applying the getTitle method with a search string argument.

{
    "name": "contactTilesWithText",
    "type": "tutorial/contactTile",
    "public": true,
    "selector": {
        "css": "example-contact-tile",
        "returnAll": true
    },
    "filter": {
        "apply": "getTitle",
        "matcher": {
            "type": "stringContains",
            "args": [
                {
                    "name": "contactTileTitleText",
                    "type": "string"
                }
            ]
        }
    }
}

The filter applies the getTitle method to the selected example-contact-tile elements.

The getTitle method is defined in the JSON page object for example-contact-tile.

"methods": [
    {
        "name": "getTitle",
        "compose": [
            {
                "element": "contactTileTitle",
                "apply": "getText"
            }
        ]
    }
],

To filter by contact title, the inner element, example-contact-tile, must expose a getTitle method that returns the element text by using getText. The apply property in the outer element references the getTitle method.

The generated getContactTilesWithText method iterates through the contact tiles and returns any elements whose title satisfies the matcher criteria in the filter (stringContains 'VP'). Since the filter doesn't specify a findFirst property, the generated method returns an array.

The test loops over the returned elements to assert that each contact title includes 'VP'.

Click Run Test.