From 91e9483f8e9ffcbca067406161b23e3fc74d0e99 Mon Sep 17 00:00:00 2001 From: Pavel Feldman Date: Mon, 16 Aug 2021 18:13:42 -0700 Subject: [PATCH] docs: clarify locators strictness (#8243) --- docs/src/api/class-locator.md | 45 +++++++++++++++++++++++++++++++++++ types/types.d.ts | 13 ++++++++++ 2 files changed, 58 insertions(+) diff --git a/docs/src/api/class-locator.md b/docs/src/api/class-locator.md index db54f1a919..8fc5d01843 100644 --- a/docs/src/api/class-locator.md +++ b/docs/src/api/class-locator.md @@ -95,6 +95,51 @@ await locator.HoverAsync(); await locator.ClickAsync(); ``` +**Strictness** + +Locators are strict. This means that all operations on locators that imply +some target DOM element will throw if more than one element matches given +selector. + +```js +// Throws if there are several buttons in DOM: +await page.locator('button').click(); + +// Works because we explicitly tell locator to pick the first element: +await page.locator('button').first().click(); +``` + +```python async +# Throws if there are several buttons in DOM: +await page.locator('button').click() + +# Works because we explicitly tell locator to pick the first element: +await page.locator('button').first.click() +``` + +```python sync +# Throws if there are several buttons in DOM: +page.locator('button').click() + +# Works because we explicitly tell locator to pick the first element: +page.locator('button').first.click() +``` + +```java +// Throws if there are several buttons in DOM: +page.locator("button").click(); + +// Works because you explicitly tell locator to pick the first element: +page.locator("button").first().click(); +``` + +```csharp +// Throws if there are several buttons in DOM: +await page.Locator("button").ClickAsync(); +// Works because you explicitly tell locator to pick the first element: +await page.Locator("button").First.ClickAsync(); +``` + ## async method: Locator.allInnerTexts - returns: <[Array]<[string]>> diff --git a/types/types.d.ts b/types/types.d.ts index aff44ebf0e..cff6557dc5 100644 --- a/types/types.d.ts +++ b/types/types.d.ts @@ -7029,6 +7029,19 @@ export interface ElementHandle extends JSHandle { * await locator.click(); * ``` * + * **Strictness** + * + * Locators are strict. This means that all operations on locators that imply some target DOM element will throw if more + * than one element matches given selector. + * + * ```js + * // Throws if there are several buttons in DOM: + * await page.locator('button').click(); + * + * // Works because we explicitly tell locator to pick the first element: + * await page.locator('button').first().click(); + * ``` + * */ export interface Locator { /**