Selector.withText Method

Finds an element whose content includes the specified text.



Selector().withText(text) → Selector

Selects elements that contain the specified text.

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.


Selector().withText(re) → Selector

Selects elements whose text content matches the specified regular expression.

Argument Type Description
re RegExp A regular expression that should match the element's text.


// Selects label elements that contain 'foo'.
// Matches 'foo', 'foobar'. Does not match 'bar', 'Foo'.

// Selects div elements whose text matches
// the /a[b-e]/ regular expression.
// Matches 'ab', 'ac'. Does not match 'bb', 'aa'.


withText selects the element that contains the specified text and its ancestors.

Consider the following markup.

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

A selector that targets div elements with the text foo matches both elements (the parent followed by the child).

// This selector matches the parent div (.container)
// and then the child div (.child)

To target elements with HTML symbols or HTML entities (e.g., &nbsp;, newline chars), refer to the following section: Select Elements That Contain Special Characters.