WebdriverIO Selectors: CSS, Text, Role and $$
On this page
Every WebdriverIO test is a sequence of "find this element, then do something with it". $ finds one element, $$ finds all matching elements, and the string you pass decides how they search. This chapter covers the selector strategies you will actually use on web pages, how to chain them, and what WebdriverIO 10's strict $ means for your tests.
Create test/specs/selectors.e2e.ts:
import { $, $$, browser, expect } from '@wdio/globals'
describe('Selectors', () => {
it('finds elements by CSS, role and text', async () => {
await browser.url('/login')
await $('role/textbox[name="Username"]').setValue('tomsmith')
await $('#password').setValue('SuperSecretPassword!')
await $('button=Login').click()
await expect($('h2*=Secure Area')).toBeDisplayed()
await expect($('*=Logout')).toBeClickable()
})
})
browser.url('/login') opens https://the-internet.herokuapp.com/login because chapter 1 set baseUrl. The rest of the test uses four different selector strategies.
The strategies worth knowing#
CSS selectors are the default: any string WebdriverIO does not recognise as something else is passed to the browser as CSS. #username, input[name="q"], #checkboxes input:not(:checked) all work. CSS is fast and precise, but it couples the test to markup that users never see; an id or a data-testid attribute is fine, a chain of layout classes is not.
Role selectors find an element the way assistive technology sees it: role/<role>, optionally with [name="<accessible name>"]. role/textbox[name="Username"] finds the text field labelled "Username", whatever its id or classes. The name has to match the full accessible name. Not every element has a role: a password field has none, which is why the spec falls back to #password.
Accessible name selectors, aria/<name>, match any element whose accessible name is the given text, from aria-label, aria-labelledby, alt, title or its content. They are convenient, but they do not care what kind of element they hit (more on that below).
Text selectors match by visible text:
| Selector | Finds |
|---|---|
=Logout |
a link whose text is exactly "Logout" |
*=Log |
a link whose text contains "Log" |
button=Start |
a <button> whose text is exactly "Start" |
h2*=Secure Area |
an <h2> whose text contains "Secure Area" |
.=logout, .*=log
|
the same, case-insensitive |
The tag in front of = can be any element name, and it is what keeps text selectors precise: button=Start will not match a paragraph that happens to say "Start". You cannot mix a CSS combinator into a text selector ($('header h1*=Welcome') does not work); chain instead, as shown below.
XPath (//button[text()="Login"]) is supported, and sometimes the only way to reach an element by its relationship to another. Treat it as a last resort; it is the hardest to read and the easiest to break.
The WebdriverIO documentation ranks them roughly like this: text and role selectors first, then aria/ and data-testid, then ids and attributes sparingly, and never generic tags or styling classes on their own. The reasoning is the same in every framework: a selector should describe what the user sees, so it survives a redesign that does not change what the user sees.
A designer replaces the Login button's classes and moves it into a different wrapper. The button still says "Login". Which selector keeps working without a change?
The tag and the visible text are what the user sees, and neither changed. Class names and positional XPath both depend on markup that was just rewritten.
A cross-browser surprise with aria/#
The first version of this spec used $('aria/Password') for the password field. It passed in Chrome. On Firefox, both on TestingBot and locally, it failed with:
StrictSelectorError: strict mode violation: `$("aria/Password")` resolved to 2 elements, expected 1.
The page has a <label for="password">Password</label> next to the input, and in Firefox the lookup returned both, the label first. In Safari on TestingBot there was no error at that line at all: the login silently did not happen, and the test only failed later, when the "Secure Area" heading never appeared. aria/Login has a similar catch on this page: it returns the <i> element inside the button, not the button. aria/ asks "which elements are called this?", and the answer can include more than the control you meant. Two lessons follow. First, prefer a selector that also states what kind of element you want: a role selector, an id, or a tag-qualified text selector. Second, run the suite in more than one browser before trusting a selector; chapter 6 makes that a single command.
$$ and lists of elements#
$$ returns all matches as an array-like ElementArray. You can check its length, index into it, and loop over it:
it('works with lists of elements', async () => {
await browser.url('/checkboxes')
const boxes = $$('#checkboxes input')
await expect(boxes).toBeElementsArrayOfSize(2)
await boxes[0].click()
for await (const box of boxes) {
await expect(box).toBeSelected()
}
})
The practice page has two checkboxes, the second already ticked. The test ticks the first and checks both. Note that boxes is not awaited when it is created: $$ returns a chainable promise, and indexing (boxes[0]) or for await resolves it when needed. The same is true of $, which is why you can write $('#username').setValue(...) without a separate await $(...).
Strict $ and chaining#
Add a third test:
it('throws when $ matches more than one element', async () => {
await browser.url('/checkboxes')
await expect($('#checkboxes input').click())
.rejects.toThrow(/resolved to 2 elements/)
await $('#checkboxes').$('input:not(:checked)').click()
})
$('#checkboxes input') matches both checkboxes. Older WebdriverIO versions silently clicked the first one; version 10 throws a StrictSelectorError and its message lists your options: use $$ to work with all matches, $$(...)[0] when you really mean the first, or narrow the selector. That is what the last line does, in two ways at once: it chains $ calls, searching inside #checkboxes only, and it adds :not(:checked) so exactly one element matches.
Chaining is also how you combine strategies. $('#login').$('button=Login') scopes a text selector to a form, which a single selector string cannot express.
You can opt out of strictness for one call with $('#checkboxes input', { strict: false }), or for the whole project with strictSelectors: false in wdio.conf.ts. Do that only while migrating an old suite. A selector that matches two elements is usually a bug waiting to happen: the day the page order changes, the test clicks the wrong one.
After upgrading to WebdriverIO 10, await $('.product button').click() throws a StrictSelectorError on a page with 12 products. You want to add the third product to the cart. What do you write?
Index the list of products explicitly, then search inside the one you want. Turning strictness off clicks the first match, which is the wrong product, and catching the error just hides it.
Shadow DOM#
Custom elements often render their content in a shadow root, which document.querySelector cannot see. Since version 9, WebdriverIO's $ and $$ pierce open shadow roots automatically, so a chain such as $('my-login').$('button=Sign in') reaches a button inside a custom element's shadow root without special syntax.
Run it#
npx wdio run wdio.conf.ts --spec test/specs/selectors.e2e.ts
[chrome 157.0.8103.78 mac #0-0] Selectors
[chrome 157.0.8103.78 mac #0-0] ✓ finds elements by CSS, role and text
[chrome 157.0.8103.78 mac #0-0] ✓ works with lists of elements
[chrome 157.0.8103.78 mac #0-0] ✓ throws when $ matches more than one element
[chrome 157.0.8103.78 mac #0-0]
[chrome 157.0.8103.78 mac #0-0] 3 passing (3s)
You need the "Delete" button that belongs to the row containing "Conway" in a table. Which approach fits WebdriverIO best?
Text selectors cannot be combined with CSS combinators in one string, and a bare button=Delete matches every row's button (strict mode would throw). Narrow down to the row first, then chain.