# WebdriverIO v10 documentation: Writing Tests > 17 pages. Index of all sections: https://webdriver.io/llms.txt --- Source: https://webdriver.io/docs/selectors.md # Selectors The [WebDriver Protocol](https://w3c.github.io/webdriver/) provides several selector strategies to query an element. WebdriverIO simplifies them to keep selecting elements simple. Please note that even though the command to query elements is called `$` and `$$`, they have nothing to do with jQuery or the [Sizzle Selector Engine](https://github.com/jquery/sizzle). While there are so many different selectors available, only a few of them provide a resilient way to find the right element. For example, given the following button: ``` ``` We **do** and **do not** recommend the following selectors: | Selector | Recommended | Notes | | ------------------------------------------ | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `$('button')` | 🚨 Never | Worst - too generic, no context. | | `$('.btn.btn-large')` | 🚨 Never | Bad. Coupled to styling. Highly subject to change. | | `$('#main')` | ⚠️ Sparingly | Better. But still coupled to styling or JS event listeners. | | `$(() => document.queryElement('button'))` | ⚠️ Sparingly | Effective querying, complex to write. | | `$('button[name="submission"]')` | ⚠️ Sparingly | Coupled to the `name` attribute which has HTML semantics. | | `$('button[data-testid="submit"]')` | βœ… Good | Requires additional attribute, not connected to a11y. | | `$('aria/Submit')` | βœ… Good | Good. Resembles how the user interacts with the page. It is recommended to use translation files so your tests don't break when translations are updated. On WebDriver BiDi sessions this uses the browser accessibility tree. On Classic sessions it falls back to XPath and can be slower on large pages. | | `$('button=Submit')` | βœ… Always | Best. Resembles how the user interacts with the page and is fast. It is recommended to use translation files so your tests don't break when translations are updated. | ## Strict Mode[​](#strict-mode "Direct link to Strict Mode") As of v10 the [`$`](/docs/api/browser/$.md) command is **strict**: it represents exactly one element. If the selector matches more than one element, the command throws a `StrictSelectorError` instead of silently picking the first match: ``` // there are 12 buttons on the page await $('button').click() // StrictSelectorError: strict mode violation: `$("button")` resolved to 12 elements, expected 1. ``` This is the same behavior as [Playwright locators](https://playwright.dev/docs/locators#strictness). Cypress differs: its queries may resolve to several elements, and it is the action commands such as [`.click()`](https://docs.cypress.io/api/commands/click#Click-all-elements-with-id-starting-with-btn) that reject a multi-element subject by default. Strict mode surfaces selectors that are too broad, which would otherwise silently interact with the wrong element as soon as the page grows. The rule applies to every step of a [chain](#chain-selectors) and to every selector type `$` accepts β€” string selectors (including ones that pierce the shadow DOM), [JS functions](#js-function), [mobile selectors](#mobile-selectors) and [custom strategy](#custom-selector-strategies) references. ### What is not affected[​](#what-is-not-affected "Direct link to What is not affected") * `$$` keeps returning zero or many elements, as an [`ElementArray`](/docs/api/browser/$$.md). Await the list (or its `.length`) before you read the count or use `for...of`. `for await` works on the list directly. * The dedicated helper commands `custom$`, `shadow$` and `react$` are not strict β€” they still return their first match, as do their `$$` counterparts. * A selector that matches nothing still returns a lazily-resolved element, so [`waitForExist`](/docs/api/element/waitForExist.md) and the [auto-waiting](/docs/autowait.md) behavior are unchanged. * Passing an element reference, e.g. `$(await browser.getActiveElement())`, always refers to a single node and is never checked. Migrating to v10 For how to audit your suite for strict-mode violations, narrow or opt out of individual queries, and disable strict mode project-wide, see the [v10 migration guide](/docs/v10-migration.md). ## CSS Query Selector[​](#css-query-selector "Direct link to CSS Query Selector") If not indicated otherwise, WebdriverIO will query elements using the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors) pattern, e.g.: selectors/example.js ``` loading... ``` [View on GitHub]() ## Link Text[​](#link-text "Direct link to Link Text") To get an anchor element with a specific text in it, query the text starting with an equals (`=`) sign. For example: selectors/example.html ``` loading... ``` [View on GitHub]() You can query this element by calling: selectors/example.js ``` loading... ``` [View on GitHub]() ## Partial Link Text[​](#partial-link-text "Direct link to Partial Link Text") To find a anchor element whose visible text partially matches your search value, query it by using `*=` in front of the query string (e.g. `*=driver`). You can query the element from the example above by also calling: selectors/example.js ``` loading... ``` [View on GitHub]() **Note:** You can't mix multiple selector strategies in one selector. Use multiple chained element queries to reach the same goal, e.g.: ``` const elem = await $('header h1*=Welcome') // doesn't work!!! // use instead const elem = await $('header').$('*=driver') ``` ## Element with certain text[​](#element-with-certain-text "Direct link to Element with certain text") The same technique can be applied to elements as well. Additionally, it is also possible to do a case-insensitive matching using `.=` or `.*=` within the query. For example, here's a query for a level 1 heading with the text "Welcome to my Page": selectors/example.html ``` loading... ``` [View on GitHub]() You can query this element by calling: selectors/example.js ``` loading... ``` [View on GitHub]() Or using query partial text: selectors/example.js ``` loading... ``` [View on GitHub]() The same works for `id` and `class` names: selectors/example.html ``` loading... ``` [View on GitHub]() You can query this element by calling: selectors/example.js ``` loading... ``` [View on GitHub]() **Note:** You can't mix multiple selector strategies in one selector. Use multiple chained element queries to reach the same goal, e.g.: ``` const elem = await $('header h1*=Welcome') // doesn't work!!! // use instead const elem = await $('header').$('h1*=Welcome') ``` ## Tag Name[​](#tag-name "Direct link to Tag Name") To query an element with a specific tag name, use `` or ``. selectors/example.html ``` loading... ``` [View on GitHub]() You can query this element by calling: selectors/example.js ``` loading... ``` [View on GitHub]() ## Name Attribute[​](#name-attribute "Direct link to Name Attribute") For querying elements with a specific name attribute, use a CSS selector such as `[name="some-name"]`. On a mobile session that same shorthand is sent with Appium's `name` locator strategy: selectors/example.html ``` loading... ``` [View on GitHub]() selectors/example.js ``` loading... ``` [View on GitHub]() **Note:** The `name` locator strategy is an Appium locator. Desktop sessions keep `[name="some-name"]` on the CSS strategy. ## xPath[​](#xpath "Direct link to xPath") It is also possible to query elements via a specific [xPath](https://developer.mozilla.org/en-US/docs/Web/XPath). An xPath selector has a format like `//body/div[6]/div[1]/span[1]`. selectors/xpath.html ``` loading... ``` [View on GitHub]() You can query the second paragraph by calling: selectors/example.js ``` loading... ``` [View on GitHub]() You can use xPath to also traverse up and down the DOM tree: selectors/example.js ``` loading... ``` [View on GitHub]() ## Accessibility Name Selector[​](#accessibility-name-selector "Direct link to Accessibility Name Selector") Query elements by their accessible name. The accessible name is what is announced by a screen reader when that element receives focus. The value of the accessible name can be both visual content or hidden text alternatives. On [WebDriver BiDi](https://w3c.github.io/webdriver-bidi/) sessions (Chrome, Edge, Firefox and other BiDi-capable browsers) WebdriverIO first uses [`browsingContext.locateNodes`](https://w3c.github.io/webdriver-bidi/#command-browsingContext-locateNodes) with an accessibility locator. That queries the browser accessibility tree directly and is typically much faster than the XPath approximation. If the accessibility locator finds nothing, WebdriverIO falls back to the Classic XPath heuristic so existing `aria/` queries keep matching. info You can read more about this selector in our [release blog post](/blog/2022/09/05/accessibility-selector) ### Fetch by `aria-label`[​](#fetch-by-aria-label "Direct link to fetch-by-aria-label") selectors/aria.html ``` loading... ``` [View on GitHub]() selectors/example.js ``` loading... ``` [View on GitHub]() ### Fetch by `aria-labelledby`[​](#fetch-by-aria-labelledby "Direct link to fetch-by-aria-labelledby") selectors/aria.html ``` loading... ``` [View on GitHub]() selectors/example.js ``` loading... ``` [View on GitHub]() ### Fetch by content[​](#fetch-by-content "Direct link to Fetch by content") selectors/aria.html ``` loading... ``` [View on GitHub]() selectors/example.js ``` loading... ``` [View on GitHub]() ### Fetch by title[​](#fetch-by-title "Direct link to Fetch by title") selectors/aria.html ``` loading... ``` [View on GitHub]() selectors/example.js ``` loading... ``` [View on GitHub]() ### Fetch by `alt` property[​](#fetch-by-alt-property "Direct link to fetch-by-alt-property") selectors/aria.html ``` loading... ``` [View on GitHub]() selectors/example.js ``` loading... ``` [View on GitHub]() ## Role Selector[​](#role-selector "Direct link to Role Selector") Query elements by their ARIA role and accessible name, the way a screen reader describes them: "the *Add to cart* button". A role plus a name keeps matching when class names, test ids or the DOM structure change. ``` await $('role/button[name="Add to cart"]').click() await expect($('role/heading[name="Order summary"]')).toBeDisplayed() // role only const rows = await $$('role/row') // scoped to a parent element const dialog = $('role/dialog[name="Checkout"]') await dialog.$('role/button[name="Pay now"]').click() ``` The syntax is `role/` or `role/[name=""]`. Single quotes work too, and a quote inside the name is escaped with a backslash: `role/button[name="Say \"hi\""]`. * The name has to match the full accessible name. * The role has to be an ARIA role. A typo fails with the closest valid role, for example `"buton" is not an ARIA role. Did you mean "button"?`. * `img` and its ARIA 1.3 name `image` are the same role. * The selector follows the [strict mode](#strict-mode) of `$` like every other selector. On a [WebDriver BiDi](https://w3c.github.io/webdriver-bidi/) session, WebdriverIO passes role and name to [`browsingContext.locateNodes`](https://w3c.github.io/webdriver-bidi/#command-browsingContext-locateNodes). The browser computes both itself, the same way assistive technology sees the page. Elements inside open shadow roots and inside frames, including frames from another origin, are found. If the browser finds no element, there is no fallback to a heuristic. Note that the browser decides the role: for example, a `` without headers or caption can be a layout table, and its rows then have no `row` role. On a WebDriver Classic session, and when a browser does not support the role locator, WebdriverIO computes role and accessible name in the page with [`dom-accessibility-api`](https://github.com/eps1lon/dom-accessibility-api), the implementation Testing Library uses. A text field without a label is named by its `placeholder`, as browsers do. The role selector is not available in a native mobile app context. Use an [accessibility id](#accessibility-id) there. ## ARIA - Role Attribute[​](#aria---role-attribute "Direct link to ARIA - Role Attribute") For querying elements based on [ARIA roles](https://www.w3.org/TR/html-aria/#docconformance), you can directly specify role of the element like `[role=button]` as selector parameter. This selector approximates the role from the element name and attributes. Prefer the [role selector](#role-selector), which uses the role the browser computes and can also match the accessible name: selectors/aria.html ``` loading... ``` [View on GitHub]() selectors/example.js ``` loading... ``` [View on GitHub]() ## ID Attribute[​](#id-attribute "Direct link to ID Attribute") Locator strategy "id" is not supported in WebDriver protocol, one should use either CSS or xPath selector strategies instead to find elements using ID. However some drivers (e.g. [Appium You.i Engine Driver](https://github.com/YOU-i-Labs/appium-youiengine-driver#selector-strategies)) might still [support](https://github.com/YOU-i-Labs/appium-youiengine-driver#selector-strategies) this selector. Current supported selector syntaxes for ID are: ``` //css locator const button = await $('#someid') //xpath locator const button = await $('//*[@id="someid"]') //id strategy // Note: works only in Appium or similar frameworks which supports locator strategy "ID" const button = await $('id=resource-id/iosname') ``` ## JS Function[​](#js-function "Direct link to JS Function") You can also use JavaScript functions to fetch elements using web native APIs. Of course, you can only do this inside a web context (e.g., `browser`, or web context in mobile). Given the following HTML structure: selectors/js.html ``` loading... ``` [View on GitHub]() You can query the sibling element of `#elem` as follows: selectors/example.js ``` loading... ``` [View on GitHub]() ## Deep Selectors[​](#deep-selectors "Direct link to Deep Selectors") warning Starting with `v9` of WebdriverIO there is no need for this special selector as WebdriverIO automatically pierces through the Shadow DOM for you. It is recommended to migrate off this selector by removing the `>>>` in front it. On a WebDriver BiDi session, `$` and `$$` look into every open shadow root: roots created with `attachShadow()` and declarative shadow roots (`