Selector.withText Method

Finds elements with an innerText or textContent value that contains the specified string. The text argument is case-sensitive — consult the case sensitivity section for a workaround.

Syntax

withText(text)

Selector().withText(text) → Selector

Finds elements with a textContent value that contains the specified string.

Argument Type Description
text String The element’s text content. The text argument is case-sensitive.

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

withText(re)

Selector().withText(re) → Selector

Finds elements with a textContent value that matches the regular expression.

Argument Type Description
re RegExp Regular expression query.

Case Sensitivity

The text argument is case-sensitive. To ignore letter case, create a regular expression with your query as outlined below.

Regular expressions are search patterns. When you pass a regular expression to the withText method, TestCafe resolves the search pattern and looks for all elements that match it. If you include the /i flag in your regular expression, the search pattern ignores the letter case of your query.

Examples

// Selects label elements that contain 'foo'.
// Matches 'foo', 'foobar'. Does not match 'bar', 'Foo'.
const elWithTextFoo = Selector('label').withText('foo');

// Selects div elements whose text matches
// the /a[b-e]/ regular expression.
// Matches 'ab', 'ac'. Does not match 'bb', 'aa'.
const elWithRegExp = Selector('div').withText(/a[b-e]/);

// Selects label elements that contain 'foo' (case-insensitive).
// Matches 'foo', 'FOO', 'Foo', 'FooBar'.
const elWithCaseInsFoo = Selector('label').withText(/foo/i);

Query results and the DOM Tree

The withText and withExactText methods match all the elements that contain the query string. It doesn’t matter whether the string descends directly from the element, or from one of its children. As long as TestCafe finds the string somewhere inside the target element, it’s a successful match.

Consider this piece of markup:

<div class="container">
    <div class="child">foo</div>
</div>

The following query matches both the .container class div and the .child class div.

// This selector matches the parent div (.container)
// and then the child div (.child)
const elWithChild = Selector('div').withText('foo');

Target elements with special characters

To target elements with HTML symbols and entities (for example, &nbsp;, newline characters), refer to the Select Elements That Contain Special Characters recipe.