Element Selectors

  • 14 minutes to read

Element selectors identify webpage elements in tests. You can use element selectors to define target elements for on-page actions and assertions.

Create Element Selectors

There are two ways to create element selectors:

Auto-Generated Element Selectors

TestCafe Studio can generate element selectors while recording in the following cases:

  • When you interact with a webpage.

    TestCafe Studio records on-page actions, generates element selectors for target elements, and adds them to the Element Selector parameter.

    Element selector

  • When you pick a webpage element with the element picker.

    To pick a target element on the page, click the Pick a target element button (the Element Picker icon) next to the Element Selector field in the test action parameters area, and select the element on the webpage. TestCafe Studio generates element selectors for this element and adds one of the selectors to the Element Selector parameter. For some elements, you can expand the list to select another generated selector.

    Picking an element

Element Selector Types

TestCafe Studio produces a set of element selectors for each target element. To see all the available element selectors, click the button next to the CSS Selector input.

Element selectors list

The following selector types are available:

Type Matching Element Examples Default Priority
tagName An element with the specified tag name. These selectors can match the <html>, <body>, <header>, <footer>, and <main> elements only. 'body' 1
id An element with the specified ID. 1. matches an element with id="populate" : '#populate'
2. matches an element with an auto-generated id:
'div' > withAttribute('id', /test1_ctl\d+_test2/)
2
text An element with the specified innerText property.
For <option> elements, TestCafe uses a textContent property to generate element selectors.
'p' > withText('Hello world!') 3
class An element with the specified class attribute value. [class="container"] 4
attr An element with the specified attribute.
The following attributes can be used: alt, name, title, and data-* (unless you create a custom selector type for the attribute).
1. one attribute: '[name="name"]'
2. multiple attributes: '.some-class[alt="someAlt"]' > withAttribute('data-attr', /foo\s+bar/)
5
dom An element at the specified position in the DOM hierarchy. 'body' > find('form') > find('div') > find('header') > find('h1') 6

Custom Attribute Selectors

To ensure selectors return the same elements after page modifications, you can add custom element identifiers for testing purposes. For example, assign the data-test-id attribute to all elements on your website that are part of the tests.

TestCafe Studio can generate selectors based on these custom attributes. Open the Selector Generation pane in the Record Configuration Dialog, click Add Custom Attribute, and specify its name.

Adding a custom attribute

You can drag and drop this selector type to set its priority (we recommend top priority for custom attributes).

Compound Selectors

TestCafe Studio also generates compound selectors that consist of base (identifies a parent element) and child (identifies its desired descendant) parts. These parts have different types in compound selectors for additional reliability.

The following combinations are used:

Base Part Child Part
customAttr
tagName
id
class
attr
customAttr
text
class
attr
dom

Examples

Compound Type Description Example
id > text Finds an element with the specified ID and its descendants with the specified text. '#side-panel' > find('span') > withText('View Docs')
attr > dom Finds an element with the specified attribute and its descendants by their position in the DOM. [label="OS"] > find('option') > find('p') > child('span')

Selector Type Priority

TestCafe Studio allows you to specify which selector types the Recorder should prefer when it generates element selectors.

The following scenarios are examples where you may need to customize selector generation:

  • You want to use a custom attribute (like data-testid) as the primary element identifier in tests.
  • The site you are testing uses dynamic IDs and you want TestCafe Studio to ignore them when it generates selectors.
  • DOM structure on the page changes frequently and you want to adjust selector generation based on these changes.

To set the selector type priority, open the Selector Generation pane in the Record Configuration Dialog (you can do this while recording) and reorder the selector types in the list (the top-most item has the highest priority). You can also disable built-in and add new selector types on this pane.

Drag and drop selector types

A Compound selector's priority is defined by its base part. When the Recorder compares selectors whose base parts are of the same type, it takes into account the child part's priorities.

For instance, consider the following selector type priority setting:

Compound selector example

With this setting, TestCafe Studio prioritizes compound selectors as follows:

  1. data-testid
  2. data-testid > class
  3. data-testid > dom
  4. class
  5. class > data-testid
  6. class > dom
  7. dom

Elements Highlighting

When you focus or modify the CSS selector in the action parameters, you can see all the matching elements highlighted on the webpage. The feature is only available during recording.

Highlighted element

Element Selector Constructor

Use the element selector constructor to create an element selector. The constructor allows you to specify a base selector and add methods to extend this selector.

The constructor is available:

Example

The animation below demonstrates how to create an element selector that:

  1. finds all ul elements on a page;
  2. finds label elements in each ul element;
  3. finds a parent that matches the div.container selector for each label element.

Then you can use the created element selector in on-page actions, for example, in the Click action.

Element selector constructor

NOTE
  • An element selector can return multiple elements. If you use this selector in an on-page action, the action is performed on the first matching element. If you use it in an assertion, the assertion checks properties for the first element.

  • If added methods filter out all elements, an element selector returns null. If a test action or an assertion uses this selector, the test fails.

Base Selector

In the element selector constructor, you first specify a base selector that returns a matching set of elements.

The base selector can be one of the following types:

  • CSS Selector - A CSS selector string that matches one or more elements. For example, you can specify #submit-button for a webpage element with id="submit-button".

    Selector type

  • Function - A regular function that returns an element or array of elements. Use functions when you need to implement custom logic to get a target element.

    Selector type

    NOTE

    You cannot use the following within this function:

  • Element Selector - A stored element selector that you define in the Define Element Selector action. You can use this selector or extend it with selector methods.

    Selector type

NOTE

If you specify a selector in the constructor during recording, all matching elements are highlighted on the webpage.

Add Selector Methods

In the element selector constructor, you can add one or more element selector methods to filter the matching set or search for related elements. The methods are called one by one.

To add a method, click the Add Method button and select a method in the list.

Add method

Specify the method's parameters (if needed) and click Done.

Method parameters

Remove Methods

To remove a method, select it in the constructor and click the Remove button.

Remove method

Reorder Methods

You can drag the added methods to reorder them.

Reuse Element Selectors

The Define Element Selector action allows you to create an element selector and use it later in the test.

To create an element selector:

  1. Add the Define Element Selector action from the Actions panel.

  2. Specify the element selector's name in the Name field.

    NOTE

    Selector names must be unique in a test. You cannot use the following reserved words: t, fixture, test, Selector, ClientFunction, RequestLogger, RequestMock, RequestHook.

  3. Use the element selector constructor to define the element selector.

Action icon

You can use the created element selectors in on-page actions and assertions. The main benefits are:

  • The element selector's short name makes tests easier to read.

  • You can define an element selector once and use it in multiple test actions. If the tested webpage changes, edit the element selector in the Define Element Selector action. There is no need to edit other actions, which makes your tests easier to maintain.

    Benefits

Element Selector Timeout

When an on-page action or an assertion uses an element selector, TestCafe Studio waits for the target element to appear in the DOM hierarchy and become visible within the element selector timeout. You can set the timeout in the run configuration's Advanced options.

If TestCafe Studio cannot find the target element in the DOM, the test fails.

See Wait for an Action's Target Element for more information.

Element Selector Methods

The element selector constructor includes two groups of selector methods:

Filter Elements

The Filter Elements group contains methods that filter a matching set returned by a base selector.

nth(index)

Finds an element by its index in a matching set. The index parameter is zero-based. If index is negative, the index starts from the end of a matching set.

For example:

  • nth(2) - Selects the third element.
  • nth(-1) - Selects the last element.

withText(text)

Filters a matching set by the specified text. Selects elements that contain this text. The text parameter is case-sensitive.

To filter elements by strict match, use the withExactText method.

withText(re)

Filters a matching set using the specified regular expression, for example, withText(/a[b-e]/).

withExactText(text)

Filters a matching set by the specified text. Selects elements whose text content strictly matches this text. The text parameter is case-sensitive.

To search for elements that contain specific text, use the withText method.

withAttribute(attrName)

Finds elements that contain the specified attribute.

The Attribute Name parameter is a string or a regular expression.

For example, withAttribute('myAttr') selects elements that have the myAttr attribute. This attribute can have any value.

withAttribute(attrName, attrValue)

Finds elements that contain the specified attribute with the specified value.

The Attribute Name and Attribute Value parameters are strings or regular expressions.

For example:

  • withAttribute('attrName', 'foo') - Selects elements whose attrName attribute is set to foo. Does not match the otherAttr attribute, or the attrName attribute with the foobar value.

  • withAttribute(/[123]z/, /a[0-9]/) - Selects elements that have an attribute whose name matches the /[123]z/ regular expression. This attribute must have a value that matches the /a[0-9]/ regular expression. Matches the '1z' and '3z' attributes with the 'a0' and 'a7' values. Does not match the '4z' or '1b' attribute, as well as any attribute with the 'b0' or 'ab' value.

filterVisible()

Filters a matching set leaving only visible elements. These are elements that do not have the display: none or visibility: hidden CSS properties and have a non-zero width and height.

filterHidden()

Filters a matching set leaving only hidden elements. These are elements that have the display: none or visibility: hidden CSS property or a zero width or height.

filter(cssSelector)

Finds elements that match the specified CSS selector.

For example, filter('.someClass') selects elements that have the someClass class.

filter(filterFunction)

Filters elements using filterFunction. This function takes each element in a matching set and checks if the element satisfies the specified conditions.

The function takes the following parameters:

Parameter Description
node The current DOM node.
idx The current node's index among other nodes in a matching set.
NOTE

You cannot use the following within the filter function:

The Search for Related Elements group contains methods that find related elements for elements returned by a base selector.

find

  • find(cssSelector) - Finds all descendants of all elements in a matching set and filters them by the specified CSS selector.

  • find(filterFunction) - Finds all descendants of all elements in a matching set and filters them with the filter function.

parent

  • parent() - Finds all parents of all elements in a matching set (the first element in the set is the closest parent).

  • parent(index) - Finds all parents of all elements in a matching set and filters them by index (0 is the closest). If index is negative, the index starts from the end of a matching set.

  • parent(cssSelector) - Finds all parents of all elements in a matching set and filters them by the specified CSS selector.

  • parent(filterFunction) - Finds all parents of all elements in a matching set and filters them with the filter function.

child

  • child() - Finds all child elements of all elements in a matching set.

  • child(index) - Finds all child elements of all elements in a matching set and filters them by index. The index parameter is zero-based. If index is negative, the index starts from the end of a matching set.

  • child(cssSelector) - Finds all child elements of all elements in a matching set and filters them by the specified CSS selector.

  • child(filterFunction) - Finds all child elements of all elements in a matching set and filters them with the filter function.

sibling

  • sibling() - Finds all sibling elements of all elements in a matching set.

  • sibling(index) - Finds all sibling elements of all elements in a matching set and filters them by index. The index parameter is zero-based. If index is negative, the index starts from the end of a matching set.

  • sibling(cssSelector) - Finds all sibling elements of all elements in a matching set and filters them by the specified CSS selector.

  • sibling(filterFunction) - Finds all sibling elements of all elements in a matching set and filters them with the filter function.

nextSibling

  • nextSibling() - Finds all succeeding sibling elements of all elements in a matching set.

  • nextSibling(index) - Finds all succeeding sibling elements of all elements in a matching set and filters them by index. The index parameter is zero-based. If index is negative, the index starts from the end of a matching set.

  • nextSibling(cssSelector) - Finds all succeeding sibling elements of all elements in a matching set and filters them by cssSelector.

  • nextSibling(filterFunction) - Finds all succeeding sibling elements of all elements in a matching set and filters them with the filter function.

prevSibling

  • prevSibling() - Finds all preceding sibling elements of all elements in a matching set.

  • prevSibling(index) - Finds all preceding sibling elements of all elements in a matching set and filters them by index. The index parameter is zero-based. If index is negative, the index starts from the end of a matching set.

  • prevSibling(cssSelector) - Finds all preceding sibling elements of all elements in a matching set and filters them by the specified CSS selector.

  • prevSibling(filterFunction) - Finds all preceding sibling elements of all elements in a matching set and uses the filter function to apply filters.

shadowRoot

  • shadowRoot() - Finds the shadow root of an element. Chain other selector methods to traverse the shadow DOM. Throws an error if the shadow tree is closed or does not exist.
NOTE

You cannot perform actions with a node returned by shadowRoot() or use it in assertions.

Only use this element as an entry point for shadow DOM.

Filter Elements with a Function

The Search for Related Elements methods allow you to filter a matching set with a filter function. The function takes each element in the matching set and checks if the element meets some condition.

The function accepts the following parameters:

Parameter Description
node The current matching node.
idx The current node's index.
originNode The node whose parents/siblings/children is being iterated.

The following example demonstrates how to use a filter function in the find method:

Filter function

NOTE

You cannot use the following within the filter function:

Test the Shadow DOM

The Visual Test Recorder does not record actions performed with shadow DOM elements. Use the Actions panel to add actions that interact with the shadow DOM.

The shadow DOM elements are inaccessible from the DOM directly. To interact with the shadow DOM, identify the root node of a shadow tree with the shadowRoot selector method. Use other selector methods to traverse the shadow tree.

The example below types text in an <input type="text"> element. The element is located inside a shadow tree hosted by a div. The shadowRoot method selects the root node of a shadow tree. The find method locates the desired element inside the shadow DOM.

Accessing the Shadow DOM

TIP

You can save the root element with the Define Element Selector action to reuse it later.

WARNING

You cannot perform actions on the element returned by shadowRoot() or use it in assertions. Use this element as an entry point to the shadow DOM and traverse the shadow tree from there.