Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

docs: add usage sections to Locator methods (#19968)

Dmitry Gozman7d2cc06355a9
diff --git a/docs/src/api/class-locator.md b/docs/src/api/class-locator.md
index 9dfb391f60..c1fbdb2f6a 100644
--- a/docs/src/api/class-locator.md
+++ b/docs/src/api/class-locator.md
@@ -46,12 +46,56 @@ foreach (var li in await page.GetByRole('listitem').AllAsync())
Returns an array of `node.innerText` values for all matching nodes.
+**Usage**
+
+```js
+const texts = await page.getByRole('link').allInnerTexts();
+```
+
+```python async
+texts = await page.get_by_role("link").all_inner_texts()
+```
+
+```python sync
+texts = page.get_by_role("link").all_inner_texts()
+```
+
+```java
+String[] texts = page.getByRole(AriaRole.LINK).allInnerTexts();
+```
+
+```csharp
+var texts = await page.GetByRole(AriaRole.Link).AllInnerTextsAsync();
+```
+
## async method: Locator.allTextContents
* since: v1.14
- returns: <[Array]<[string]>>
Returns an array of `node.textContent` values for all matching nodes.
+**Usage**
+
+```js
+const texts = await page.getByRole('link').allTextContents();
+```
+
+```python async
+texts = await page.get_by_role("link").all_text_contents()
+```
+
+```python sync
+texts = page.get_by_role("link").all_text_contents()
+```
+
+```java
+String[] texts = page.getByRole(AriaRole.LINK).allTextContents();
+```
+
+```csharp
+var texts = await page.GetByRole(AriaRole.Link).AllTextContentsAsync();
+```
+
## async method: Locator.blur
* since: v1.28
@@ -68,9 +112,11 @@ Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur)
- `width` <[float]> the width of the element in pixels.
- `height` <[float]> the height of the element in pixels.
-This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is
+This method returns the bounding box of the element matching the locator, or `null` if the element is not visible. The bounding box is
calculated relative to the main frame viewport - which is usually the same as the browser window.
+**Details**
+
Scrolling affects the returned bounding box, similarly to
[Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). That
means `x` and/or `y` may be negative.
@@ -84,27 +130,27 @@ snippet should click the center of the element.
**Usage**
```js
-const box = await element.boundingBox();
+const box = await page.getByRole('button').boundingBox();
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
```
```java
-BoundingBox box = element.boundingBox();
+BoundingBox box = page.getByRole(AriaRole.BUTTON).boundingBox();
page.mouse().click(box.x + box.width / 2, box.y + box.height / 2);
```
```python async
-box = await element.bounding_box()
+box = await page.get_by_role("button").bounding_box()
await page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
```
```python sync
-box = element.bounding_box()
+box = page.get_by_role("button").bounding_box()
page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
```
```csharp
-var box = await element.BoundingBoxAsync();
+var box = await page.GetByRole(AriaRole.Button).BoundingBoxAsync();
await page.Mouse.ClickAsync(box.X + box.Width / 2, box.Y + box.Height / 2);
```
@@ -114,7 +160,11 @@ await page.Mouse.ClickAsync(box.X + box.Width / 2, box.Y + box.Height / 2);
## async method: Locator.check
* since: v1.14
-This method checks the element by performing the following steps:
+Ensure that checkbox or radio element is checked.
+
+**Details**
+
+Performs the following steps:
1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
checked, this method returns immediately.
1. Wait for [actionability](../actionability.md) checks on the element, unless [`option: force`] option is set.
@@ -128,6 +178,28 @@ If the element is detached from the DOM at any moment during the action, this me
When all steps combined have not finished during the specified [`option: timeout`], this method throws a
[TimeoutError]. Passing zero timeout disables this.
+**Usage**
+
+```js
+await page.getByRole('checkbox').check();
+```
+
+```java
+page.getByRole(AriaRole.CHECKBOX).check();
+```
+
+```python async
+await page.get_by_role("checkbox").check()
+```
+
+```python sync
+page.get_by_role("checkbox").check()
+```
+
+```csharp
+await page.GetByRole(AriaRole.Checkbox).CheckAsync();
+```
+
### option: Locator.check.position = %%-input-position-%%
* since: v1.14
@@ -146,10 +218,38 @@ When all steps combined have not finished during the specified [`option: timeout
## async method: Locator.clear
* since: v1.28
+Clear the input field.
+
+**Details**
+
This method waits for [actionability](../actionability.md) checks, focuses the element, clears it and triggers an `input` event after clearing.
If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error. However, if the element is inside the `<label>` element that has an associated [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be cleared instead.
+
+**Usage**
+
+```js
+await page.getByRole('textbox').clear();
+```
+
+```java
+page.getByRole(AriaRole.TEXTBOX).clear();
+```
+
+```python async
+await page.get_by_role("textbox").clear()
+```
+
+```python sync
+page.get_by_role("textbox").clear()
+```
+
+```csharp
+await page.GetByRole(AriaRole.Textbox).ClearAsync();
+```
+
+
### option: Locator.clear.force = %%-input-force-%%
* since: v1.28
@@ -177,6 +277,69 @@ If the element is detached from the DOM at any moment during the action, this me
When all steps combined have not finished during the specified [`option: timeout`], this method throws a
[TimeoutError]. Passing zero timeout disables this.
+
+**Usage**
+
+Click a button:
+
+```js
+await page.getByRole('button').click();
+```
+
+```java
+page.getByRole(AriaRole.BUTTON).click();
+```
+
+```python async
+await page.get_by_role("button").click()
+```
+
+```python sync
+page.get_by_role("button").click()
+```
+
+```csharp
+await page.GetByRole(AriaRole.Button).ClickAsync();
+```
+
+Shift-right-click at a specific position on a canvas:
+
+```js
+await page.locator('canvas').click({
+ button: 'right',
+ modifiers: ['Shift'],
+ position: { x: 23, y: 32 },
+});
+```
+
+```java
+page.locator("canvas").click(new Locator.ClickOptions()
+ .setButton(MouseButton.RIGHT)
+ .setModifiers(Arrays.asList(KeyboardModifier.SHIFT))
+ .setPosition(23, 32));
+```
+
+```python async
+await page.locator("canvas").click(
+ button="right", modifiers=["Shift"], position={"x": 23, "y": 32}
+)
+```
+
+```python sync
+page.locator("canvas").click(
+ button="right", modifiers=["Shift"], position={"x": 23, "y": 32}
+)
+```
+
+```csharp
+await page.Locator("canvas").ClickAsync(new() {
+ Button = MouseButton.Right,
+ Modifiers = new[] { KeyboardModifier.Shift },
+ Position = new Position { X = 0, Y = 0 }
+});
+```
+
+
### option: Locator.click.button = %%-input-button-%%
* since: v1.14
@@ -208,13 +371,40 @@ When all steps combined have not finished during the specified [`option: timeout
* since: v1.14
- returns: <[int]>
-Returns the number of elements matching given selector.
+Returns the number of elements matching the locator.
+
+**Usage**
+
+```js
+const count = await page.getByRole('listitem').count();
+```
+
+```python async
+count = await page.get_by_role("listitem").count()
+```
+
+```python sync
+count = page.get_by_role("listitem").count()
+```
+
+```java
+int count = page.getByRole(AriaRole.LISTITEM).count();
+```
+
+```csharp
+int count = await page.GetByRole(AriaRole.Listitem).CountAsync();
+```
+
## async method: Locator.dblclick
* since: v1.14
* langs:
- alias-csharp: DblClickAsync
+Double-click an element.
+
+**Details**
+
This method double clicks the element by performing the following steps:
1. Wait for [actionability](../actionability.md) checks on the element, unless [`option: force`] option is set.
1. Scroll the element into view if needed.
@@ -258,32 +448,36 @@ When all steps combined have not finished during the specified [`option: timeout
## async method: Locator.dispatchEvent
* since: v1.14
-The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element, `click`
-is dispatched. This is equivalent to calling
-[element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+Programmaticaly dispatch an event on the matching element.
**Usage**
```js
-await element.dispatchEvent('click');
+await locator.dispatchEvent('click');
```
```java
-element.dispatchEvent("click");
+locator.dispatchEvent("click");
```
```python async
-await element.dispatch_event("click")
+await locator.dispatch_event("click")
```
```python sync
-element.dispatch_event("click")
+locator.dispatch_event("click")
```
```csharp
-await element.DispatchEventAsync("click");
+await locator.DispatchEventAsync("click");
```
+**Details**
+
+The snippet above dispatches the `click` event on the element. Regardless of the visibility state of the element, `click`
+is dispatched. This is equivalent to calling
+[element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+
Under the hood, it creates an instance of an event based on the given [`param: type`], initializes it with
[`param: eventInit`] properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by
default.
@@ -298,12 +492,12 @@ properties:
* [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
* [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
-You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
+You can also specify [JSHandle] as the property value if you want live objects to be passed into the event:
```js
// Note you can only create DataTransfer in Chromium and Firefox
const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
-await element.dispatchEvent('dragstart', { dataTransfer });
+await locator.dispatchEvent('dragstart', { dataTransfer });
```
```java
@@ -311,24 +505,24 @@ await element.dispatchEvent('dragstart', { dataTransfer });
JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()");
Map<String, Object> arg = new HashMap<>();
arg.put("dataTransfer", dataTransfer);
-element.dispatchEvent("dragstart", arg);
+locator.dispatchEvent("dragstart", arg);
```
```python async
# note you can only create data_transfer in chromium and firefox
data_transfer = await page.evaluate_handle("new DataTransfer()")
-await element.dispatch_event("#source", "dragstart", {"dataTransfer": data_transfer})
+await locator.dispatch_event("#source", "dragstart", {"dataTransfer": data_transfer})
```
```python sync
# note you can only create data_transfer in chromium and firefox
data_transfer = page.evaluate_handle("new DataTransfer()")
-element.dispatch_event("#source", "dragstart", {"dataTransfer": data_transfer})
+locator.dispatch_event("#source", "dragstart", {"dataTransfer": data_transfer})
```
```csharp
var dataTransfer = await page.EvaluateHandleAsync("() => new DataTransfer()");
-await element.DispatchEventAsync("dragstart", new Dictionary<string, object>
+await locator.DispatchEventAsync("dragstart", new Dictionary<string, object>
{
{ "dataTransfer", dataTransfer }
});
@@ -352,6 +546,10 @@ Optional event-specific initialization properties.
## async method: Locator.dragTo
* since: v1.18
+Drag the source element towards the target element and drop it.
+
+**Details**
+
This method drags the locator to another target locator or target position. It will
first move to the source element, perform a `mousedown`, then move to the target
element or position and perform a `mouseup`.
@@ -447,7 +645,7 @@ Locator of the element to drag to.
* since: v1.14
- returns: <[ElementHandle]>
-Resolves given locator to the first matching DOM element. If no elements matching the query are visible, waits for them up to a given timeout. If multiple elements match the selector, throws.
+Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If multiple elements match the locator, throws.
### option: Locator.elementHandle.timeout = %%-input-timeout-%%
* since: v1.14
@@ -456,18 +654,21 @@ Resolves given locator to the first matching DOM element. If no elements matchin
* since: v1.14
- returns: <[Array]<[ElementHandle]>>
-Resolves given locator to all matching DOM elements.
+Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
## async method: Locator.evaluate
* since: v1.14
- returns: <[Serializable]>
-Returns the return value of [`param: expression`].
+Execute JavaScript code in the page, taking the matching element as an argument.
-This method passes this handle as the first argument to [`param: expression`].
+**Details**
+
+Returns the return value of [`param: expression`], called with the matching element as a first argument, and [`param: arg`] as a second argument.
-If [`param: expression`] returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return
-its value.
+If [`param: expression`] returns a [Promise], this method will wait for the promise to resolve and return its value.
+
+If [`param: expression`] throws or rejects, this method throws.
**Usage**
@@ -512,37 +713,41 @@ Optional argument to pass to [`param: expression`].
* since: v1.14
- returns: <[Serializable]>
-The method finds all elements matching the specified locator and passes an array of matched elements as
-a first argument to [`param: expression`]. Returns the result of [`param: expression`] invocation.
+Execute JavaScript code in the page, taking all matching elements as an argument.
+
+**Details**
+
+Returns the return value of [`param: expression`], called with an array of all matching elements as a first argument, and [`param: arg`] as a second argument.
-If [`param: expression`] returns a [Promise], then [`method: Locator.evaluateAll`] would wait for the promise
-to resolve and return its value.
+If [`param: expression`] returns a [Promise], this method will wait for the promise to resolve and return its value.
+
+If [`param: expression`] throws or rejects, this method throws.
**Usage**
```js
-const elements = page.locator('div');
-const divCounts = await elements.evaluateAll((divs, min) => divs.length >= min, 10);
+const locator = page.locator('div');
+const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10);
```
```java
-Locator elements = page.locator("div");
-boolean divCounts = (boolean) elements.evaluateAll("(divs, min) => divs.length >= min", 10);
+Locator locator = page.locator("div");
+boolean moreThanTen = (boolean) locator.evaluateAll("(divs, min) => divs.length > min", 10);
```
```python async
-elements = page.locator("div")
-div_counts = await elements.evaluate_all("(divs, min) => divs.length >= min", 10)
+locator = page.locator("div")
+more_than_ten = await locator.evaluate_all("(divs, min) => divs.length > min", 10)
```
```python sync
-elements = page.locator("div")
-div_counts = elements.evaluate_all("(divs, min) => divs.length >= min", 10)
+locator = page.locator("div")
+more_than_ten = locator.evaluate_all("(divs, min) => divs.length > min", 10)
```
```csharp
-var elements = page.Locator("div");
-var divsCount = await elements.EvaluateAllAsync<bool>("(divs, min) => divs.length >= min", 10);
+var locator = page.Locator("div");
+var moreThanTen = await locator.EvaluateAllAsync<bool>("(divs, min) => divs.length > min", 10);
```
### param: Locator.evaluateAll.expression = %%-evaluate-expression-%%
@@ -558,14 +763,17 @@ Optional argument to pass to [`param: expression`].
* since: v1.14
- returns: <[JSHandle]>
-Returns the return value of [`param: expression`] as a [JSHandle].
+Execute JavaScript code in the page, taking the matching element as an argument, and return a [JSHandle] with the result.
-This method passes this handle as the first argument to [`param: expression`].
+**Details**
+
+Returns the return value of [`param: expression`] as a[JSHandle], called with the matching element as a first argument, and [`param: arg`] as a second argument.
The only difference between [`method: Locator.evaluate`] and [`method: Locator.evaluateHandle`] is that [`method: Locator.evaluateHandle`] returns [JSHandle].
-If the function passed to the [`method: Locator.evaluateHandle`] returns a [Promise], then [`method: Locator.evaluateHandle`] would wait
-for the promise to resolve and return its value.
+If [`param: expression`] returns a [Promise], this method will wait for the promise to resolve and return its value.
+
+If [`param: expression`] throws or rejects, this method throws.
See [`method: Page.evaluateHandle`] for more details.
@@ -584,6 +792,32 @@ Optional argument to pass to [`param: expression`].
## async method: Locator.fill
* since: v1.14
+Set a value to the input field.
+
+**Usage**
+
+```js
+await page.getByRole('textbox').fill('example value');
+```
+
+```java
+page.getByRole(AriaRole.TEXTBOX).fill("example value");
+```
+
+```python async
+await page.get_by_role("textbox").fill("example value")
+```
+
+```python sync
+page.get_by_role("textbox").fill("example value")
+```
+
+```csharp
+await page.GetByRole(AriaRole.Textbox).FillAsync("example value");
+```
+
+**Details**
+
This method waits for [actionability](../actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string to clear the input field.
If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error. However, if the element is inside the `<label>` element that has an associated [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled instead.
@@ -675,7 +909,7 @@ Returns locator to the first matching element.
## async method: Locator.focus
* since: v1.14
-Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
+Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
### option: Locator.focus.timeout = %%-input-timeout-%%
* since: v1.14
@@ -684,11 +918,11 @@ Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
* since: v1.17
- returns: <[FrameLocator]>
-**Usage**
-
-When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
+When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements
in that iframe:
+**Usage**
+
```js
const locator = page.frameLocator('iframe').getByText('Submit');
await locator.click();
@@ -721,7 +955,7 @@ await locator.ClickAsync();
* since: v1.14
- returns: <[null]|[string]>
-Returns element attribute value.
+Returns the matching element's attribute value.
### param: Locator.getAttribute.name
* since: v1.14
@@ -812,6 +1046,32 @@ Highlight the corresponding element(s) on the screen. Useful for debugging, don'
## async method: Locator.hover
* since: v1.14
+Hover over the matching element.
+
+**Usage**
+
+```js
+await page.getByRole('link').hover();
+```
+
+```python async
+await page.get_by_role("link").hover()
+```
+
+```python sync
+page.get_by_role("link").hover()
+```
+
+```java
+page.getByRole(AriaRole.LINK).hover();
+```
+
+```csharp
+await page.GetByRole(AriaRole.Link).HoverAsync();
+```
+
+**Details**
+
This method hovers over the element by performing the following steps:
1. Wait for [actionability](../actionability.md) checks on the element, unless [`option: force`] option is set.
1. Scroll the element into view if needed.
@@ -845,7 +1105,7 @@ When all steps combined have not finished during the specified [`option: timeout
* since: v1.14
- returns: <[string]>
-Returns the `element.innerHTML`.
+Returns the [`element.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML).
### option: Locator.innerHTML.timeout = %%-input-timeout-%%
* since: v1.14
@@ -854,7 +1114,7 @@ Returns the `element.innerHTML`.
* since: v1.14
- returns: <[string]>
-Returns the `element.innerText`.
+Returns the [`element.innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText).
### option: Locator.innerText.timeout = %%-input-timeout-%%
* since: v1.14
@@ -863,9 +1123,33 @@ Returns the `element.innerText`.
* since: v1.14
- returns: <[string]>
-Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
+Returns the value for the matching `<input>` or `<textarea>` or `<select>` element.
+
+**Usage**
+
+```js
+const value = await page.getByRole('textbox').inputValue();
+```
+
+```python async
+value = await page.get_by_role("textbox").input_value()
+```
+
+```python sync
+value = page.get_by_role("textbox").input_value()
+```
+
+```java
+String value = page.getByRole(AriaRole.TEXTBOX).inputValue();
+```
+
+```csharp
+String value = await page.GetByRole(AriaRole.Textbox).InputValueAsync();
+```
+
+**Details**
-Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the control.
+Throws elements that are not an input, textarea or a select. However, if the element is inside the `<label>` element that has an associated [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the control.
### option: Locator.inputValue.timeout = %%-input-timeout-%%
* since: v1.14
@@ -876,6 +1160,28 @@ Throws for non-input elements. However, if the element is inside the `<label>` e
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
+**Usage**
+
+```js
+const checked = await page.getByRole('checkbox').isChecked();
+```
+
+```java
+boolean checked = page.getByRole(AriaRole.CHECKBOX).isChecked();
+```
+
+```python async
+checked = await page.get_by_role("checkbox").is_checked()
+```
+
+```python sync
+checked = page.get_by_role("checkbox").is_checked()
+```
+
+```csharp
+Boolean checked = await page.GetByRole(AriaRole.Checkbox).IsCheckedAsync();
+```
+
### option: Locator.isChecked.timeout = %%-input-timeout-%%
* since: v1.14
@@ -885,6 +1191,28 @@ Returns whether the element is checked. Throws if the element is not a checkbox
Returns whether the element is disabled, the opposite of [enabled](../actionability.md#enabled).
+**Usage**
+
+```js
+const disabled = await page.getByRole('button').isDisabled();
+```
+
+```java
+boolean disabled = page.getByRole(AriaRole.BUTTON).isDisabled();
+```
+
+```python async
+disabled = await page.get_by_role("button").is_disabled()
+```
+
+```python sync
+disabled = page.get_by_role("button").is_disabled()
+```
+
+```csharp
+Boolean disabled = await page.GetByRole(AriaRole.Button).IsDisabledAsync();
+```
+
### option: Locator.isDisabled.timeout = %%-input-timeout-%%
* since: v1.14
@@ -894,6 +1222,28 @@ Returns whether the element is disabled, the opposite of [enabled](../actionabil
Returns whether the element is [editable](../actionability.md#editable).
+**Usage**
+
+```js
+const editable = await page.getByRole('textbox').isEditable();
+```
+
+```java
+boolean editable = page.getByRole(AriaRole.TEXTBOX).isEditable();
+```
+
+```python async
+editable = await page.get_by_role("textbox").is_editable()
+```
+
+```python sync
+editable = page.get_by_role("textbox").is_editable()
+```
+
+```csharp
+Boolean editable = await page.GetByRole(AriaRole.Textbox).IsEditableAsync();
+```
+
### option: Locator.isEditable.timeout = %%-input-timeout-%%
* since: v1.14
@@ -903,6 +1253,28 @@ Returns whether the element is [editable](../actionability.md#editable).
Returns whether the element is [enabled](../actionability.md#enabled).
+**Usage**
+
+```js
+const enabled = await page.getByRole('button').isEnabled();
+```
+
+```java
+boolean enabled = page.getByRole(AriaRole.BUTTON).isEnabled();
+```
+
+```python async
+enabled = await page.get_by_role("button").is_enabled()
+```
+
+```python sync
+enabled = page.get_by_role("button").is_enabled()
+```
+
+```csharp
+Boolean enabled = await page.GetByRole(AriaRole.Button).IsEnabledAsync();
+```
+
### option: Locator.isEnabled.timeout = %%-input-timeout-%%
* since: v1.14
@@ -912,6 +1284,28 @@ Returns whether the element is [enabled](../actionability.md#enabled).
Returns whether the element is hidden, the opposite of [visible](../actionability.md#visible).
+**Usage**
+
+```js
+const hidden = await page.getByRole('button').isHidden();
+```
+
+```java
+boolean hidden = page.getByRole(AriaRole.BUTTON).isHidden();
+```
+
+```python async
+hidden = await page.get_by_role("button").is_hidden()
+```
+
+```python sync
+hidden = page.get_by_role("button").is_hidden()
+```
+
+```csharp
+Boolean hidden = await page.GetByRole(AriaRole.Button).IsHiddenAsync();
+```
+
### option: Locator.isHidden.timeout
* since: v1.14
* deprecated: This option is ignored. [`method: Locator.isHidden`] does not wait for the element to become hidden and returns immediately.
@@ -923,6 +1317,28 @@ Returns whether the element is hidden, the opposite of [visible](../actionabilit
Returns whether the element is [visible](../actionability.md#visible).
+**Usage**
+
+```js
+const visible = await page.getByRole('button').isVisible();
+```
+
+```java
+boolean visible = page.getByRole(AriaRole.BUTTON).isVisible();
+```
+
+```python async
+visible = await page.get_by_role("button").is_visible()
+```
+
+```python sync
+visible = page.get_by_role("button").is_visible()
+```
+
+```csharp
+Boolean visible = await page.GetByRole(AriaRole.Button).IsVisibleAsync();
+```
+
### option: Locator.isVisible.timeout
* since: v1.14
* deprecated: This option is ignored. [`method: Locator.isVisible`] does not wait for the element to become visible and returns immediately.
@@ -934,6 +1350,28 @@ Returns whether the element is [visible](../actionability.md#visible).
Returns locator to the last matching element.
+**Usage**
+
+```js
+const banana = await page.getByRole('listitem').last();
+```
+
+```python async
+banana = await page.get_by_role("listitem").last()
+```
+
+```python sync
+banana = page.get_by_role("listitem").last()
+```
+
+```java
+Locator banana = page.getByRole(AriaRole.LISTITEM).last();
+```
+
+```csharp
+var banana = await page.GetByRole(AriaRole.Listitem).Last(1);
+```
+
## method: Locator.locator
* since: v1.14
- returns: <[Locator]>
@@ -952,6 +1390,28 @@ Returns locator to the last matching element.
Returns locator to the n-th matching element. It's zero based, `nth(0)` selects the first element.
+**Usage**
+
+```js
+const banana = await page.getByRole('listitem').nth(2);
+```
+
+```python async
+banana = await page.get_by_role("listitem").nth(2)
+```
+
+```python sync
+banana = page.get_by_role("listitem").nth(2)
+```
+
+```java
+Locator banana = page.getByRole(AriaRole.LISTITEM).nth(2);
+```
+
+```csharp
+var banana = await page.GetByRole(AriaRole.Listitem).Nth(2);
+```
+
### param: Locator.nth.index
* since: v1.14
- `index` <[int]>
@@ -965,6 +1425,32 @@ A page this locator belongs to.
## async method: Locator.press
* since: v1.14
+Focuses the mathing element and presses a combintation of the keys.
+
+**Usage**
+
+```js
+await page.getByRole('textbox').press('Backspace');
+```
+
+```java
+page.getByRole(AriaRole.TEXTBOX).press("Backspace");
+```
+
+```python async
+await page.get_by_role("textbox").press("Backspace")
+```
+
+```python sync
+page.get_by_role("textbox").press("Backspace")
+```
+
+```csharp
+await page.GetByRole(AriaRole.Textbox).PressAsync("Backspace");
+```
+
+**Details**
+
Focuses the element, and then uses [`method: Keyboard.down`] and [`method: Keyboard.up`].
[`param: key`] can specify the intended
@@ -1007,6 +1493,59 @@ Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
* since: v1.14
- returns: <[Buffer]>
+Take a screenshot of the element matching the locator.
+
+**Usage**
+
+```js
+await page.getByRole('link').screenshot();
+```
+
+```java
+page.getByRole(AriaRole.LINK).screenshot();
+```
+
+```python async
+await page.get_by_role("link").screenshot()
+```
+
+```python sync
+page.get_by_role("link").screenshot()
+```
+
+```csharp
+await page.GetByRole(AriaRole.Link).ScreenshotAsync();
+```
+
+Disable animations and save screenshot to a file:
+
+```js
+await page.getByRole('link').screenshot({ animations: 'disabled', path: 'link.png' });
+```
+
+```java
+page.getByRole(AriaRole.LINK).screenshot(new Locator.ScreenshotOptions()
+ .setAnimations(ScreenshotAnimations.DISABLED)
+ .setPath(Paths.get("example.png")));
+```
+
+```python async
+await page.get_by_role("link").screenshot(animations="disabled", path="link.png")
+```
+
+```python sync
+page.get_by_role("link").screenshot(animations="disabled", path="link.png")
+```
+
+```csharp
+await page.GetByRole(AriaRole.Link).ScreenshotAsync(new() {
+ Animations = ScreenshotAnimations.Disabled,
+ Path = "link.png"
+});
+```
+
+**Details**
+
This method captures a screenshot of the page, clipped to the size and position of a particular element matching the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the element is a scrollable container, only the currently scrolled content will be visible on the screenshot.
This method waits for the [actionability](../actionability.md) checks, then scrolls element into view before taking a
@@ -1129,6 +1668,32 @@ If the element is inside the `<label>` element that has an associated [control](
## async method: Locator.setChecked
* since: v1.15
+Set the state of a checkbox or a radio element.
+
+**Usage**
+
+```js
+await page.getByRole('checkbox').setChecked(true);
+```
+
+```java
+page.getByRole(AriaRole.CHECKBOX).setChecked(true);
+```
+
+```python async
+await page.get_by_role("checkbox").set_checked(True)
+```
+
+```python sync
+page.get_by_role("checkbox").set_checked(True)
+```
+
+```csharp
+await page.GetByRole(AriaRole.Checkbox).SetCheckedAsync(true);
+```
+
+**Details**
+
This method checks or unchecks an element by performing the following steps:
1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
1. If the element already has the right checked state, this method returns immediately.
@@ -1163,6 +1728,101 @@ When all steps combined have not finished during the specified [`option: timeout
## async method: Locator.setInputFiles
* since: v1.14
+Upload file or multiple files into `<input type=file>`.
+
+**Usage**
+
+```js
+// Select one file
+await page.getByLabel('Upload file').setInputFiles('myfile.pdf');
+
+// Select multiple files
+await page.getByLabel('Upload files').setInputFiles(['file1.txt', 'file2.txt']);
+
+// Remove all the selected files
+await page.getByLabel('Upload file').setInputFiles([]);
+
+// Upload buffer from memory
+await page.getByLabel('Upload file').setInputFiles({
+ name: 'file.txt',
+ mimeType: 'text/plain',
+ buffer: Buffer.from('this is test')
+});
+```
+
+```java
+// Select one file
+page.getByLabel("Upload file").setInputFiles(Paths.get("myfile.pdf"));
+
+// Select multiple files
+page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
+
+// Remove all the selected files
+page.getByLabel("Upload file").setInputFiles(new Path[0]);
+
+// Upload buffer from memory
+page.getByLabel("Upload file").setInputFiles(new FilePayload(
+ "file.txt", "text/plain", "this is test".getBytes(StandardCharsets.UTF_8)));
+```
+
+```python async
+# Select one file
+await page.get_by_label("Upload file").set_input_files('myfile.pdf')
+
+# Select multiple files
+await page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])
+
+# Remove all the selected files
+await page.get_by_label("Upload file").set_input_files([])
+
+# Upload buffer from memory
+await page.get_by_label("Upload file").set_input_files(
+ files=[
+ {"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
+ ],
+)
+```
+
+```python sync
+# Select one file
+page.get_by_label("Upload file").set_input_files('myfile.pdf')
+
+# Select multiple files
+page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])
+
+# Remove all the selected files
+page.get_by_label("Upload file").set_input_files([])
+
+# Upload buffer from memory
+page.get_by_label("Upload file").set_input_files(
+ files=[
+ {"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
+ ],
+)
+```
+
+```csharp
+// Select one file
+await page.GetByLabel("Upload file").SetInputFilesAsync("myfile.pdf");
+
+// Select multiple files
+await page.GetByLabel("Upload files").SetInputFilesAsync(new[] { "file1.txt", "file12.txt" });
+
+// Remove all the selected files
+await page.GetByLabel("Upload file").SetInputFilesAsync(new[] {});
+
+// Upload buffer from memory
+await page.GetByLabel("Upload file").SetInputFilesAsync(new FilePayload
+{
+ Name = "file.txt",
+ MimeType = "text/plain",
+ Buffer = System.Text.Encoding.UTF8.GetBytes("this is a test"),
+});
+```
+
+
+**Details**
+
Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they
are resolved relative to the current working directory. For empty array, clears the selected files.
@@ -1181,6 +1841,10 @@ This method expects [Locator] to point to an
## async method: Locator.tap
* since: v1.14
+Perform a tap gesture on the element matching the locator.
+
+**Details**
+
This method taps the element by performing the following steps:
1. Wait for [actionability](../actionability.md) checks on the element, unless [`option: force`] option is set.
1. Scroll the element into view if needed.
@@ -1218,7 +1882,7 @@ When all steps combined have not finished during the specified [`option: timeout
* since: v1.14
- returns: <[null]|[string]>
-Returns the `node.textContent`.
+Returns the [`node.textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent).
### option: Locator.textContent.timeout = %%-input-timeout-%%
* since: v1.14
@@ -1310,7 +1974,33 @@ Time to wait between key presses in milliseconds. Defaults to 0.
## async method: Locator.uncheck
* since: v1.14
-This method checks the element by performing the following steps:
+Ensure that checkbox or radio element is unchecked.
+
+**Usage**
+
+```js
+await page.getByRole('checkbox').uncheck();
+```
+
+```java
+page.getByRole(AriaRole.CHECKBOX).uncheck();
+```
+
+```python async
+await page.get_by_role("checkbox").uncheck()
+```
+
+```python sync
+page.get_by_role("checkbox").uncheck()
+```
+
+```csharp
+await page.GetByRole(AriaRole.Checkbox).UncheckAsync();
+```
+
+**Details**
+
+This method unchecks the element by performing the following steps:
1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
unchecked, this method returns immediately.
1. Wait for [actionability](../actionability.md) checks on the element, unless [`option: force`] option is set.
diff --git a/docs/src/api/params.md b/docs/src/api/params.md
index 9de21aa449..79d6bf956a 100644
--- a/docs/src/api/params.md
+++ b/docs/src/api/params.md
@@ -1201,7 +1201,41 @@ Locator is resolved to the element immediately before performing an action, so a
## template-locator-get-by-test-id
-Locate element by the test id. By default, the `data-testid` attribute is used as a test id. Use [`method: Selectors.setTestIdAttribute`] to configure a different test id attribute if necessary.
+Locate element by the test id.
+
+**Usage**
+
+Consider the following DOM structure.
+
+```html
+<button data-testid="directions">Itinéraire</button>
+```
+
+You can locate the element by it's test id:
+
+```js
+await page.getByTestId('directions').click();
+```
+
+```java
+page.getByTestId("directions").click();
+```
+
+```python async
+await page.get_by_test_id("directions").click()
+```
+
+```python sync
+page.get_by_test_id("directions").click()
+```
+
+```csharp
+await page.GetByTestId("directions").ClickAsync();
+```
+
+**Details**
+
+By default, the `data-testid` attribute is used as a test id. Use [`method: Selectors.setTestIdAttribute`] to configure a different test id attribute if necessary.
```js
// Set custom test id attribute from @playwright/test config:
@@ -1212,7 +1246,14 @@ use: {
## template-locator-get-by-text
-Allows locating elements that contain given text. Consider the following DOM structure:
+Allows locating elements that contain given text.
+
+See also [`method: Locator.filter`] that allows to match by another criteria, like an accessible role, and then filter by the text content.
+
+
+**Usage**
+
+Consider the following DOM structure:
```html
<div>Hello <span>world</span></div>
@@ -1306,53 +1347,228 @@ page.GetByText(new Regex("Hello"))
page.GetByText(new Regex("^hello$", RegexOptions.IgnoreCase))
```
-See also [`method: Locator.filter`] that allows to match by another criteria, like an accessible role, and then filter by the text content.
+**Details**
-:::note
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
-:::
-:::note
Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
-:::
## template-locator-get-by-alt-text
-Allows locating elements by their alt text. For example, this method will find the image by alt text "Castle":
+Allows locating elements by their alt text.
+
+**Usage**
+
+For example, this method will find the image by alt text "Playwright logo":
```html
-<img alt='Castle'>
+<img alt='Playwright logo'>
+```
+
+```js
+await page.getByAltText('Playwright logo').click();
+```
+
+```java
+page.getByAltText("Playwright logo").click();
+```
+
+```python async
+await page.get_by_alt_text("Playwright logo").click()
+```
+
+```python sync
+page.get_by_alt_text("Playwright logo").click()
+```
+
+```csharp
+await page.GetByAltText("Playwright logo").ClickAsync();
```
## template-locator-get-by-label-text
-Allows locating input elements by the text of the associated label. For example, this method will find the input by label text "Password" in the following DOM:
+Allows locating input elements by the text of the associated label.
+
+**Usage**
+
+For example, this method will find the input by label text "Password" in the following DOM:
```html
<label for="password-input">Password:</label>
<input id="password-input">
```
+```js
+await page.getByLabel('Password').fill('secret');
+```
+
+```java
+page.getByLabel("Password").fill("secret");
+```
+
+```python async
+await page.get_by_label("Password").fill("secret")
+```
+
+```python sync
+page.get_by_label("Password").fill("secret")
+```
+
+```csharp
+await page.GetByLabel("Password").FillAsync("secret");
+```
+
## template-locator-get-by-placeholder-text
-Allows locating input elements by the placeholder text. For example, this method will find the input by placeholder "Country":
+Allows locating input elements by the placeholder text.
+
+**Usage**
+
+For example, consider the following DOM structure.
```html
-<input placeholder="Country">
+<input type="email" placeholder="[email protected]" />
+```
+
+You can fill the input after locating it by the placeholder text:
+
+```js
+await page
+ .getByPlaceholder("[email protected]")
+ .fill("[email protected]");
+```
+
+```java
+page.getByPlaceholder("[email protected]").fill("[email protected]");
+```
+
+```python async
+await page.get_by_placeholder("[email protected]").fill("[email protected]")
+```
+
+```python sync
+page.get_by_placeholder("[email protected]").fill("[email protected]")
+```
+
+```csharp
+await page
+ .GetByPlaceholder("[email protected]")
+ .FillAsync("[email protected]");
```
## template-locator-get-by-role
-Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles), [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). Note that role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
+Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles), [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+
+**Usage**
+
+Consider the following DOM structure.
+
+```html
+<h3>Sign up</h3>
+<label>
+ <input type="checkbox" /> Subscribe
+</label>
+<br/>
+<button>Submit</button>
+```
+
+You can locate each element by it's implicit role:
+
+```js
+await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
-Note that many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings) that is recognized by the role selector. You can find all the [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
+await page.getByRole('checkbox', { name: 'Subscribe' }).check();
+
+await page.getByRole('button', { name: /submit/i }).click();
+```
+
+```python async
+await expect(page.get_by_role("heading", name="Sign up")).to_be_visible()
+
+await page.get_by_role("checkbox", name="Subscribe").check()
+
+await page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
+```
+
+```python sync
+expect(page.get_by_role("heading", name="Sign up")).to_be_visible()
+
+page.get_by_role("checkbox", name="Subscribe").check()
+
+page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
+```
+
+```java
+assertThat(page
+ .getByRole(AriaRole.HEADING,
+ new Page.GetByRoleOptions().setName("Sign up")))
+ .isVisible();
+
+page.getByRole(AriaRole.CHECKBOX,
+ new Page.GetByRoleOptions().setName("Subscribe"))
+ .check();
+
+page.getByRole(AriaRole.BUTTON,
+ new Page.GetByRoleOptions().setName(
+ Pattern.compile("submit", Pattern.CASE_INSENSITIVE)))
+ .click();
+```
+
+```csharp
+await Expect(page
+ .GetByRole(AriaRole.Heading, new() { Name = "Sign up" }))
+ .ToBeVisibleAsync();
+
+await page
+ .GetByRole(AriaRole.Checkbox, new() { Name = "Subscribe" })
+ .CheckAsync();
+
+await page
+ .GetByRole(AriaRole.Button, new() {
+ NameRegex = new Regex("submit", RegexOptions.IgnoreCase)
+ })
+ .ClickAsync();
+```
+
+**Details**
+
+Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
+
+Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings) that is recognized by the role selector. You can find all the [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
## template-locator-get-by-title
-Allows locating elements by their title. For example, this method will find the button by its title "Place the order":
+Allows locating elements by their title attribute.
+
+**Usage**
+
+Consider the following DOM structure.
```html
-<button title='Place the order'>Order Now</button>
+<span title='Issues count'>25 issues</span>
+```
+
+You can check the issues count after locating it by the title text:
+
+```js
+await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
+```
+
+```java
+assertThat(page.getByTitle("Issues count")).hasText("25 issues");
+```
+
+```python async
+await expect(page.get_by_title("Issues count")).to_have_text("25 issues")
+```
+
+```python sync
+expect(page.get_by_title("Issues count")).to_have_text("25 issues")
+```
+
+```csharp
+await Expect(page.GetByTitle("Issues count")).toHaveText("25 issues");
```
## test-config-snapshot-path-template
diff --git a/docs/src/locators.md b/docs/src/locators.md
index 422d468e7f..82728dad88 100644
--- a/docs/src/locators.md
+++ b/docs/src/locators.md
@@ -203,7 +203,7 @@ For example, consider the following DOM structure.
You can locate each element by it's implicit role:
```js
-await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible()
+await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
await page.getByRole('checkbox', { name: 'Subscribe' }).check();
@@ -1273,7 +1273,7 @@ Locator banana = page.getByRole(AriaRole.LISTITEM).nth(1);
```
```csharp
-var banana = await page.GetByRole(AriaRole.Listitem).NthAsync(1);
+var banana = await page.GetByRole(AriaRole.Listitem).Nth(1);
```
However, use this method with caution. Often times, the page might change, and the locator will point to a completely different element from the one you expected. Instead, try to come up with a unique locator that will pass the [strictness criteria](#strictness).
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 9435376b00..4d43277e74 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -2470,10 +2470,18 @@ export interface Page {
}): Promise<null|string>;
/**
- * Allows locating elements by their alt text. For example, this method will find the image by alt text "Castle":
+ * Allows locating elements by their alt text.
+ *
+ * **Usage**
+ *
+ * For example, this method will find the image by alt text "Playwright logo":
*
* ```html
- * <img alt='Castle'>
+ * <img alt='Playwright logo'>
+ * ```
+ *
+ * ```js
+ * await page.getByAltText('Playwright logo').click();
* ```
*
* @param text Text to locate the element for.
@@ -2488,14 +2496,21 @@ export interface Page {
}): Locator;
/**
- * Allows locating input elements by the text of the associated label. For example, this method will find the input by
- * label text "Password" in the following DOM:
+ * Allows locating input elements by the text of the associated label.
+ *
+ * **Usage**
+ *
+ * For example, this method will find the input by label text "Password" in the following DOM:
*
* ```html
* <label for="password-input">Password:</label>
* <input id="password-input">
* ```
*
+ * ```js
+ * await page.getByLabel('Password').fill('secret');
+ * ```
+ *
* @param text Text to locate the element for.
* @param options
*/
@@ -2508,11 +2523,22 @@ export interface Page {
}): Locator;
/**
- * Allows locating input elements by the placeholder text. For example, this method will find the input by placeholder
- * "Country":
+ * Allows locating input elements by the placeholder text.
+ *
+ * **Usage**
+ *
+ * For example, consider the following DOM structure.
*
* ```html
- * <input placeholder="Country">
+ * <input type="email" placeholder="[email protected]" />
+ * ```
+ *
+ * You can fill the input after locating it by the placeholder text:
+ *
+ * ```js
+ * await page
+ * .getByPlaceholder("[email protected]")
+ * .fill("[email protected]");
* ```
*
* @param text Text to locate the element for.
@@ -2529,14 +2555,40 @@ export interface Page {
/**
* Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
* [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
- * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). Note that role selector **does not replace**
- * accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
- *
- * Note that many html elements have an implicitly
- * [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings) that is recognized by the role selector.
- * You can find all the [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines
- * **do not recommend** duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to
- * default values.
+ * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <h3>Sign up</h3>
+ * <label>
+ * <input type="checkbox" /> Subscribe
+ * </label>
+ * <br/>
+ * <button>Submit</button>
+ * ```
+ *
+ * You can locate each element by it's implicit role:
+ *
+ * ```js
+ * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
+ *
+ * await page.getByRole('checkbox', { name: 'Subscribe' }).check();
+ *
+ * await page.getByRole('button', { name: /submit/i }).click();
+ * ```
+ *
+ * **Details**
+ *
+ * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
+ * about the ARIA guidelines.
+ *
+ * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
+ * that is recognized by the role selector. You can find all the
+ * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
+ * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
* @param role Required aria role.
* @param options
*/
@@ -2609,7 +2661,25 @@ export interface Page {
}): Locator;
/**
- * Locate element by the test id. By default, the `data-testid` attribute is used as a test id. Use
+ * Locate element by the test id.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <button data-testid="directions">Itinéraire</button>
+ * ```
+ *
+ * You can locate the element by it's test id:
+ *
+ * ```js
+ * await page.getByTestId('directions').click();
+ * ```
+ *
+ * **Details**
+ *
+ * By default, the `data-testid` attribute is used as a test id. Use
* [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)
* to configure a different test id attribute if necessary.
*
@@ -2625,7 +2695,14 @@ export interface Page {
getByTestId(testId: string|RegExp): Locator;
/**
- * Allows locating elements that contain given text. Consider the following DOM structure:
+ * Allows locating elements that contain given text.
+ *
+ * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
+ * match by another criteria, like an accessible role, and then filter by the text content.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure:
*
* ```html
* <div>Hello <span>world</span></div>
@@ -2651,14 +2728,13 @@ export interface Page {
* page.getByText(/^hello$/i)
* ```
*
- * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
- * match by another criteria, like an accessible role, and then filter by the text content.
+ * **Details**
*
- * **NOTE** Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple
- * spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
+ * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
+ * one, turns line breaks into spaces and ignores leading and trailing whitespace.
*
- * **NOTE** Input elements of the type `button` and `submit` are matched by their `value` instead of the text content.
- * For example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
+ * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
+ * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
* @param text Text to locate the element for.
* @param options
*/
@@ -2671,11 +2747,20 @@ export interface Page {
}): Locator;
/**
- * Allows locating elements by their title. For example, this method will find the button by its title "Place the
- * order":
+ * Allows locating elements by their title attribute.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
*
* ```html
- * <button title='Place the order'>Order Now</button>
+ * <span title='Issues count'>25 issues</span>
+ * ```
+ *
+ * You can check the issues count after locating it by the title text:
+ *
+ * ```js
+ * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
* ```
*
* @param text Text to locate the element for.
@@ -5774,10 +5859,18 @@ export interface Frame {
}): Promise<null|string>;
/**
- * Allows locating elements by their alt text. For example, this method will find the image by alt text "Castle":
+ * Allows locating elements by their alt text.
+ *
+ * **Usage**
+ *
+ * For example, this method will find the image by alt text "Playwright logo":
*
* ```html
- * <img alt='Castle'>
+ * <img alt='Playwright logo'>
+ * ```
+ *
+ * ```js
+ * await page.getByAltText('Playwright logo').click();
* ```
*
* @param text Text to locate the element for.
@@ -5792,14 +5885,21 @@ export interface Frame {
}): Locator;
/**
- * Allows locating input elements by the text of the associated label. For example, this method will find the input by
- * label text "Password" in the following DOM:
+ * Allows locating input elements by the text of the associated label.
+ *
+ * **Usage**
+ *
+ * For example, this method will find the input by label text "Password" in the following DOM:
*
* ```html
* <label for="password-input">Password:</label>
* <input id="password-input">
* ```
*
+ * ```js
+ * await page.getByLabel('Password').fill('secret');
+ * ```
+ *
* @param text Text to locate the element for.
* @param options
*/
@@ -5812,11 +5912,22 @@ export interface Frame {
}): Locator;
/**
- * Allows locating input elements by the placeholder text. For example, this method will find the input by placeholder
- * "Country":
+ * Allows locating input elements by the placeholder text.
+ *
+ * **Usage**
+ *
+ * For example, consider the following DOM structure.
*
* ```html
- * <input placeholder="Country">
+ * <input type="email" placeholder="[email protected]" />
+ * ```
+ *
+ * You can fill the input after locating it by the placeholder text:
+ *
+ * ```js
+ * await page
+ * .getByPlaceholder("[email protected]")
+ * .fill("[email protected]");
* ```
*
* @param text Text to locate the element for.
@@ -5833,14 +5944,40 @@ export interface Frame {
/**
* Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
* [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
- * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). Note that role selector **does not replace**
- * accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
- *
- * Note that many html elements have an implicitly
- * [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings) that is recognized by the role selector.
- * You can find all the [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines
- * **do not recommend** duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to
- * default values.
+ * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <h3>Sign up</h3>
+ * <label>
+ * <input type="checkbox" /> Subscribe
+ * </label>
+ * <br/>
+ * <button>Submit</button>
+ * ```
+ *
+ * You can locate each element by it's implicit role:
+ *
+ * ```js
+ * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
+ *
+ * await page.getByRole('checkbox', { name: 'Subscribe' }).check();
+ *
+ * await page.getByRole('button', { name: /submit/i }).click();
+ * ```
+ *
+ * **Details**
+ *
+ * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
+ * about the ARIA guidelines.
+ *
+ * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
+ * that is recognized by the role selector. You can find all the
+ * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
+ * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
* @param role Required aria role.
* @param options
*/
@@ -5913,7 +6050,25 @@ export interface Frame {
}): Locator;
/**
- * Locate element by the test id. By default, the `data-testid` attribute is used as a test id. Use
+ * Locate element by the test id.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <button data-testid="directions">Itinéraire</button>
+ * ```
+ *
+ * You can locate the element by it's test id:
+ *
+ * ```js
+ * await page.getByTestId('directions').click();
+ * ```
+ *
+ * **Details**
+ *
+ * By default, the `data-testid` attribute is used as a test id. Use
* [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)
* to configure a different test id attribute if necessary.
*
@@ -5929,7 +6084,14 @@ export interface Frame {
getByTestId(testId: string|RegExp): Locator;
/**
- * Allows locating elements that contain given text. Consider the following DOM structure:
+ * Allows locating elements that contain given text.
+ *
+ * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
+ * match by another criteria, like an accessible role, and then filter by the text content.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure:
*
* ```html
* <div>Hello <span>world</span></div>
@@ -5955,14 +6117,13 @@ export interface Frame {
* page.getByText(/^hello$/i)
* ```
*
- * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
- * match by another criteria, like an accessible role, and then filter by the text content.
+ * **Details**
*
- * **NOTE** Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple
- * spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
+ * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
+ * one, turns line breaks into spaces and ignores leading and trailing whitespace.
*
- * **NOTE** Input elements of the type `button` and `submit` are matched by their `value` instead of the text content.
- * For example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
+ * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
+ * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
* @param text Text to locate the element for.
* @param options
*/
@@ -5975,11 +6136,20 @@ export interface Frame {
}): Locator;
/**
- * Allows locating elements by their title. For example, this method will find the button by its title "Place the
- * order":
+ * Allows locating elements by their title attribute.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
*
* ```html
- * <button title='Place the order'>Order Now</button>
+ * <span title='Issues count'>25 issues</span>
+ * ```
+ *
+ * You can check the issues count after locating it by the title text:
+ *
+ * ```js
+ * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
* ```
*
* @param text Text to locate the element for.
@@ -9817,12 +9987,16 @@ export interface ElementHandle<T=Node> extends JSHandle<T> {
*/
export interface Locator {
/**
- * Returns the return value of `pageFunction`.
+ * Execute JavaScript code in the page, taking the matching element as an argument.
*
- * This method passes this handle as the first argument to `pageFunction`.
+ * **Details**
*
- * If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
- * value.
+ * Returns the return value of `pageFunction`, called with the matching element as a first argument, and `arg` as a
+ * second argument.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
*
* **Usage**
*
@@ -9839,12 +10013,16 @@ export interface Locator {
timeout?: number;
}): Promise<R>;
/**
- * Returns the return value of `pageFunction`.
+ * Execute JavaScript code in the page, taking the matching element as an argument.
*
- * This method passes this handle as the first argument to `pageFunction`.
+ * **Details**
*
- * If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
- * value.
+ * Returns the return value of `pageFunction`, called with the matching element as a first argument, and `arg` as a
+ * second argument.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
*
* **Usage**
*
@@ -9861,18 +10039,22 @@ export interface Locator {
timeout?: number;
}): Promise<R>;
/**
- * The method finds all elements matching the specified locator and passes an array of matched elements as a first
- * argument to `pageFunction`. Returns the result of `pageFunction` invocation.
+ * Execute JavaScript code in the page, taking all matching elements as an argument.
*
- * If `pageFunction` returns a [Promise], then
- * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all)
- * would wait for the promise to resolve and return its value.
+ * **Details**
+ *
+ * Returns the return value of `pageFunction`, called with an array of all matching elements as a first argument, and
+ * `arg` as a second argument.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
*
* **Usage**
*
* ```js
- * const elements = page.locator('div');
- * const divCounts = await elements.evaluateAll((divs, min) => divs.length >= min, 10);
+ * const locator = page.locator('div');
+ * const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10);
* ```
*
* @param pageFunction Function to be evaluated in the page context.
@@ -9880,18 +10062,22 @@ export interface Locator {
*/
evaluateAll<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E[], Arg, R>, arg: Arg): Promise<R>;
/**
- * The method finds all elements matching the specified locator and passes an array of matched elements as a first
- * argument to `pageFunction`. Returns the result of `pageFunction` invocation.
+ * Execute JavaScript code in the page, taking all matching elements as an argument.
*
- * If `pageFunction` returns a [Promise], then
- * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all)
- * would wait for the promise to resolve and return its value.
+ * **Details**
+ *
+ * Returns the return value of `pageFunction`, called with an array of all matching elements as a first argument, and
+ * `arg` as a second argument.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
*
* **Usage**
*
* ```js
- * const elements = page.locator('div');
- * const divCounts = await elements.evaluateAll((divs, min) => divs.length >= min, 10);
+ * const locator = page.locator('div');
+ * const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10);
* ```
*
* @param pageFunction Function to be evaluated in the page context.
@@ -9899,8 +10085,8 @@ export interface Locator {
*/
evaluateAll<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E[], void, R>): Promise<R>;
/**
- * Resolves given locator to the first matching DOM element. If no elements matching the query are visible, waits for
- * them up to a given timeout. If multiple elements match the selector, throws.
+ * Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If
+ * multiple elements match the locator, throws.
* @param options
*/
elementHandle(options?: {
@@ -9921,11 +10107,25 @@ export interface Locator {
/**
* Returns an array of `node.innerText` values for all matching nodes.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const texts = await page.getByRole('link').allInnerTexts();
+ * ```
+ *
*/
allInnerTexts(): Promise<Array<string>>;
/**
* Returns an array of `node.textContent` values for all matching nodes.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const texts = await page.getByRole('link').allTextContents();
+ * ```
+ *
*/
allTextContents(): Promise<Array<string>>;
@@ -9944,8 +10144,11 @@ export interface Locator {
}): Promise<void>;
/**
- * This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is
- * calculated relative to the main frame viewport - which is usually the same as the browser window.
+ * This method returns the bounding box of the element matching the locator, or `null` if the element is not visible.
+ * The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser
+ * window.
+ *
+ * **Details**
*
* Scrolling affects the returned bounding box, similarly to
* [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
@@ -9960,7 +10163,7 @@ export interface Locator {
* **Usage**
*
* ```js
- * const box = await element.boundingBox();
+ * const box = await page.getByRole('button').boundingBox();
* await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
* ```
*
@@ -9997,7 +10200,11 @@ export interface Locator {
}>;
/**
- * This method checks the element by performing the following steps:
+ * Ensure that checkbox or radio element is checked.
+ *
+ * **Details**
+ *
+ * Performs the following steps:
* 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
* checked, this method returns immediately.
* 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
@@ -10011,6 +10218,13 @@ export interface Locator {
*
* When all steps combined have not finished during the specified `timeout`, this method throws a [TimeoutError].
* Passing zero timeout disables this.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('checkbox').check();
+ * ```
+ *
* @param options
*/
check(options?: {
@@ -10052,6 +10266,10 @@ export interface Locator {
}): Promise<void>;
/**
+ * Clear the input field.
+ *
+ * **Details**
+ *
* This method waits for [actionability](https://playwright.dev/docs/actionability) checks, focuses the element, clears it and triggers an
* `input` event after clearing.
*
@@ -10059,6 +10277,13 @@ export interface Locator {
* error. However, if the element is inside the `<label>` element that has an associated
* [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be cleared
* instead.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('textbox').clear();
+ * ```
+ *
* @param options
*/
clear(options?: {
@@ -10099,6 +10324,25 @@ export interface Locator {
*
* When all steps combined have not finished during the specified `timeout`, this method throws a [TimeoutError].
* Passing zero timeout disables this.
+ *
+ * **Usage**
+ *
+ * Click a button:
+ *
+ * ```js
+ * await page.getByRole('button').click();
+ * ```
+ *
+ * Shift-right-click at a specific position on a canvas:
+ *
+ * ```js
+ * await page.locator('canvas').click({
+ * button: 'right',
+ * modifiers: ['Shift'],
+ * position: { x: 23, y: 32 },
+ * });
+ * ```
+ *
* @param options
*/
click(options?: {
@@ -10161,11 +10405,22 @@ export interface Locator {
}): Promise<void>;
/**
- * Returns the number of elements matching given selector.
+ * Returns the number of elements matching the locator.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const count = await page.getByRole('listitem').count();
+ * ```
+ *
*/
count(): Promise<number>;
/**
+ * Double-click an element.
+ *
+ * **Details**
+ *
* This method double clicks the element by performing the following steps:
* 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
* 1. Scroll the element into view if needed.
@@ -10237,16 +10492,20 @@ export interface Locator {
}): Promise<void>;
/**
- * The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
- * `click` is dispatched. This is equivalent to calling
- * [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+ * Programmaticaly dispatch an event on the matching element.
*
* **Usage**
*
* ```js
- * await element.dispatchEvent('click');
+ * await locator.dispatchEvent('click');
* ```
*
+ * **Details**
+ *
+ * The snippet above dispatches the `click` event on the element. Regardless of the visibility state of the element,
+ * `click` is dispatched. This is equivalent to calling
+ * [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+ *
* Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
* properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
*
@@ -10259,12 +10518,12 @@ export interface Locator {
* - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
* - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
*
- * You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
+ * You can also specify [JSHandle] as the property value if you want live objects to be passed into the event:
*
* ```js
* // Note you can only create DataTransfer in Chromium and Firefox
* const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
- * await element.dispatchEvent('dragstart', { dataTransfer });
+ * await locator.dispatchEvent('dragstart', { dataTransfer });
* ```
*
* @param type DOM event type: `"click"`, `"dragstart"`, etc.
@@ -10282,6 +10541,10 @@ export interface Locator {
}): Promise<void>;
/**
+ * Drag the source element towards the target element and drop it.
+ *
+ * **Details**
+ *
* This method drags the locator to another target locator or target position. It will first move to the source
* element, perform a `mousedown`, then move to the target element or position and perform a `mouseup`.
*
@@ -10351,14 +10614,18 @@ export interface Locator {
}): Promise<void>;
/**
- * Resolves given locator to all matching DOM elements.
+ * Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
*/
elementHandles(): Promise<Array<ElementHandle>>;
/**
- * Returns the return value of `pageFunction` as a [JSHandle].
+ * Execute JavaScript code in the page, taking the matching element as an argument, and return a [JSHandle] with the
+ * result.
*
- * This method passes this handle as the first argument to `pageFunction`.
+ * **Details**
+ *
+ * Returns the return value of `pageFunction` as a[JSHandle], called with the matching element as a first argument,
+ * and `arg` as a second argument.
*
* The only difference between
* [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate)
@@ -10368,11 +10635,9 @@ export interface Locator {
* [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
* returns [JSHandle].
*
- * If the function passed to the
- * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
- * returns a [Promise], then
- * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
- * would wait for the promise to resolve and return its value.
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
*
* See [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) for
* more details.
@@ -10391,6 +10656,16 @@ export interface Locator {
}): Promise<JSHandle>;
/**
+ * Set a value to the input field.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('textbox').fill('example value');
+ * ```
+ *
+ * **Details**
+ *
* This method waits for [actionability](https://playwright.dev/docs/actionability) checks, focuses the element, fills it and triggers an
* `input` event after filling. Note that you can pass an empty string to clear the input field.
*
@@ -10466,7 +10741,7 @@ export interface Locator {
first(): Locator;
/**
- * Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
+ * Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
* @param options
*/
focus(options?: {
@@ -10480,10 +10755,10 @@ export interface Locator {
}): Promise<void>;
/**
- * **Usage**
+ * When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements in
+ * that iframe:
*
- * When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
- * in that iframe:
+ * **Usage**
*
* ```js
* const locator = page.frameLocator('iframe').getByText('Submit');
@@ -10495,7 +10770,7 @@ export interface Locator {
frameLocator(selector: string): FrameLocator;
/**
- * Returns element attribute value.
+ * Returns the matching element's attribute value.
* @param name Attribute name to get the value for.
* @param options
*/
@@ -10510,10 +10785,18 @@ export interface Locator {
}): Promise<null|string>;
/**
- * Allows locating elements by their alt text. For example, this method will find the image by alt text "Castle":
+ * Allows locating elements by their alt text.
+ *
+ * **Usage**
+ *
+ * For example, this method will find the image by alt text "Playwright logo":
*
* ```html
- * <img alt='Castle'>
+ * <img alt='Playwright logo'>
+ * ```
+ *
+ * ```js
+ * await page.getByAltText('Playwright logo').click();
* ```
*
* @param text Text to locate the element for.
@@ -10528,14 +10811,21 @@ export interface Locator {
}): Locator;
/**
- * Allows locating input elements by the text of the associated label. For example, this method will find the input by
- * label text "Password" in the following DOM:
+ * Allows locating input elements by the text of the associated label.
+ *
+ * **Usage**
+ *
+ * For example, this method will find the input by label text "Password" in the following DOM:
*
* ```html
* <label for="password-input">Password:</label>
* <input id="password-input">
* ```
*
+ * ```js
+ * await page.getByLabel('Password').fill('secret');
+ * ```
+ *
* @param text Text to locate the element for.
* @param options
*/
@@ -10548,11 +10838,22 @@ export interface Locator {
}): Locator;
/**
- * Allows locating input elements by the placeholder text. For example, this method will find the input by placeholder
- * "Country":
+ * Allows locating input elements by the placeholder text.
+ *
+ * **Usage**
+ *
+ * For example, consider the following DOM structure.
*
* ```html
- * <input placeholder="Country">
+ * <input type="email" placeholder="[email protected]" />
+ * ```
+ *
+ * You can fill the input after locating it by the placeholder text:
+ *
+ * ```js
+ * await page
+ * .getByPlaceholder("[email protected]")
+ * .fill("[email protected]");
* ```
*
* @param text Text to locate the element for.
@@ -10569,14 +10870,40 @@ export interface Locator {
/**
* Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
* [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
- * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). Note that role selector **does not replace**
- * accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
- *
- * Note that many html elements have an implicitly
- * [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings) that is recognized by the role selector.
- * You can find all the [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines
- * **do not recommend** duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to
- * default values.
+ * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <h3>Sign up</h3>
+ * <label>
+ * <input type="checkbox" /> Subscribe
+ * </label>
+ * <br/>
+ * <button>Submit</button>
+ * ```
+ *
+ * You can locate each element by it's implicit role:
+ *
+ * ```js
+ * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
+ *
+ * await page.getByRole('checkbox', { name: 'Subscribe' }).check();
+ *
+ * await page.getByRole('button', { name: /submit/i }).click();
+ * ```
+ *
+ * **Details**
+ *
+ * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
+ * about the ARIA guidelines.
+ *
+ * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
+ * that is recognized by the role selector. You can find all the
+ * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
+ * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
* @param role Required aria role.
* @param options
*/
@@ -10649,7 +10976,25 @@ export interface Locator {
}): Locator;
/**
- * Locate element by the test id. By default, the `data-testid` attribute is used as a test id. Use
+ * Locate element by the test id.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <button data-testid="directions">Itinéraire</button>
+ * ```
+ *
+ * You can locate the element by it's test id:
+ *
+ * ```js
+ * await page.getByTestId('directions').click();
+ * ```
+ *
+ * **Details**
+ *
+ * By default, the `data-testid` attribute is used as a test id. Use
* [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)
* to configure a different test id attribute if necessary.
*
@@ -10665,7 +11010,14 @@ export interface Locator {
getByTestId(testId: string|RegExp): Locator;
/**
- * Allows locating elements that contain given text. Consider the following DOM structure:
+ * Allows locating elements that contain given text.
+ *
+ * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
+ * match by another criteria, like an accessible role, and then filter by the text content.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure:
*
* ```html
* <div>Hello <span>world</span></div>
@@ -10691,14 +11043,13 @@ export interface Locator {
* page.getByText(/^hello$/i)
* ```
*
- * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
- * match by another criteria, like an accessible role, and then filter by the text content.
+ * **Details**
*
- * **NOTE** Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple
- * spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
+ * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
+ * one, turns line breaks into spaces and ignores leading and trailing whitespace.
*
- * **NOTE** Input elements of the type `button` and `submit` are matched by their `value` instead of the text content.
- * For example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
+ * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
+ * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
* @param text Text to locate the element for.
* @param options
*/
@@ -10711,11 +11062,20 @@ export interface Locator {
}): Locator;
/**
- * Allows locating elements by their title. For example, this method will find the button by its title "Place the
- * order":
+ * Allows locating elements by their title attribute.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
*
* ```html
- * <button title='Place the order'>Order Now</button>
+ * <span title='Issues count'>25 issues</span>
+ * ```
+ *
+ * You can check the issues count after locating it by the title text:
+ *
+ * ```js
+ * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
* ```
*
* @param text Text to locate the element for.
@@ -10736,6 +11096,16 @@ export interface Locator {
highlight(): Promise<void>;
/**
+ * Hover over the matching element.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('link').hover();
+ * ```
+ *
+ * **Details**
+ *
* This method hovers over the element by performing the following steps:
* 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
* 1. Scroll the element into view if needed.
@@ -10794,7 +11164,7 @@ export interface Locator {
}): Promise<void>;
/**
- * Returns the `element.innerHTML`.
+ * Returns the [`element.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML).
* @param options
*/
innerHTML(options?: {
@@ -10808,7 +11178,7 @@ export interface Locator {
}): Promise<string>;
/**
- * Returns the `element.innerText`.
+ * Returns the [`element.innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText).
* @param options
*/
innerText(options?: {
@@ -10822,9 +11192,18 @@ export interface Locator {
}): Promise<string>;
/**
- * Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
+ * Returns the value for the matching `<input>` or `<textarea>` or `<select>` element.
*
- * Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
+ * **Usage**
+ *
+ * ```js
+ * const value = await page.getByRole('textbox').inputValue();
+ * ```
+ *
+ * **Details**
+ *
+ * Throws elements that are not an input, textarea or a select. However, if the element is inside the `<label>`
+ * element that has an associated
* [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
* control.
* @param options
@@ -10841,6 +11220,13 @@ export interface Locator {
/**
* Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const checked = await page.getByRole('checkbox').isChecked();
+ * ```
+ *
* @param options
*/
isChecked(options?: {
@@ -10855,6 +11241,13 @@ export interface Locator {
/**
* Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/docs/actionability#enabled).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const disabled = await page.getByRole('button').isDisabled();
+ * ```
+ *
* @param options
*/
isDisabled(options?: {
@@ -10869,6 +11262,13 @@ export interface Locator {
/**
* Returns whether the element is [editable](https://playwright.dev/docs/actionability#editable).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const editable = await page.getByRole('textbox').isEditable();
+ * ```
+ *
* @param options
*/
isEditable(options?: {
@@ -10883,6 +11283,13 @@ export interface Locator {
/**
* Returns whether the element is [enabled](https://playwright.dev/docs/actionability#enabled).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const enabled = await page.getByRole('button').isEnabled();
+ * ```
+ *
* @param options
*/
isEnabled(options?: {
@@ -10897,6 +11304,13 @@ export interface Locator {
/**
* Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/docs/actionability#visible).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const hidden = await page.getByRole('button').isHidden();
+ * ```
+ *
* @param options
*/
isHidden(options?: {
@@ -10910,6 +11324,13 @@ export interface Locator {
/**
* Returns whether the element is [visible](https://playwright.dev/docs/actionability#visible).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const visible = await page.getByRole('button').isVisible();
+ * ```
+ *
* @param options
*/
isVisible(options?: {
@@ -10923,6 +11344,13 @@ export interface Locator {
/**
* Returns locator to the last matching element.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const banana = await page.getByRole('listitem').last();
+ * ```
+ *
*/
last(): Locator;
@@ -10954,6 +11382,13 @@ export interface Locator {
/**
* Returns locator to the n-th matching element. It's zero based, `nth(0)` selects the first element.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const banana = await page.getByRole('listitem').nth(2);
+ * ```
+ *
* @param index
*/
nth(index: number): Locator;
@@ -10964,6 +11399,16 @@ export interface Locator {
page(): Page;
/**
+ * Focuses the mathing element and presses a combintation of the keys.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('textbox').press('Backspace');
+ * ```
+ *
+ * **Details**
+ *
* Focuses the element, and then uses
* [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) and
* [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).
@@ -11012,6 +11457,22 @@ export interface Locator {
}): Promise<void>;
/**
+ * Take a screenshot of the element matching the locator.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('link').screenshot();
+ * ```
+ *
+ * Disable animations and save screenshot to a file:
+ *
+ * ```js
+ * await page.getByRole('link').screenshot({ animations: 'disabled', path: 'link.png' });
+ * ```
+ *
+ * **Details**
+ *
* This method captures a screenshot of the page, clipped to the size and position of a particular element matching
* the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the
* element is a scrollable container, only the currently scrolled content will be visible on the screenshot.
@@ -11160,6 +11621,16 @@ export interface Locator {
}): Promise<void>;
/**
+ * Set the state of a checkbox or a radio element.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('checkbox').setChecked(true);
+ * ```
+ *
+ * **Details**
+ *
* This method checks or unchecks an element by performing the following steps:
* 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
* 1. If the element already has the right checked state, this method returns immediately.
@@ -11215,6 +11686,30 @@ export interface Locator {
}): Promise<void>;
/**
+ * Upload file or multiple files into `<input type=file>`.
+ *
+ * **Usage**
+ *
+ * ```js
+ * // Select one file
+ * await page.getByLabel('Upload file').setInputFiles('myfile.pdf');
+ *
+ * // Select multiple files
+ * await page.getByLabel('Upload files').setInputFiles(['file1.txt', 'file2.txt']);
+ *
+ * // Remove all the selected files
+ * await page.getByLabel('Upload file').setInputFiles([]);
+ *
+ * // Upload buffer from memory
+ * await page.getByLabel('Upload file').setInputFiles({
+ * name: 'file.txt',
+ * mimeType: 'text/plain',
+ * buffer: Buffer.from('this is test')
+ * });
+ * ```
+ *
+ * **Details**
+ *
* Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
* they are resolved relative to the current working directory. For empty array, clears the selected files.
*
@@ -11273,6 +11768,10 @@ export interface Locator {
}): Promise<void>;
/**
+ * Perform a tap gesture on the element matching the locator.
+ *
+ * **Details**
+ *
* This method taps the element by performing the following steps:
* 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
* 1. Scroll the element into view if needed.
@@ -11333,7 +11832,7 @@ export interface Locator {
}): Promise<void>;
/**
- * Returns the `node.textContent`.
+ * Returns the [`node.textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent).
* @param options
*/
textContent(options?: {
@@ -11394,7 +11893,17 @@ export interface Locator {
}): Promise<void>;
/**
- * This method checks the element by performing the following steps:
+ * Ensure that checkbox or radio element is unchecked.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('checkbox').uncheck();
+ * ```
+ *
+ * **Details**
+ *
+ * This method unchecks the element by performing the following steps:
* 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
* unchecked, this method returns immediately.
* 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
@@ -16094,10 +16603,18 @@ export interface FrameLocator {
frameLocator(selector: string): FrameLocator;
/**
- * Allows locating elements by their alt text. For example, this method will find the image by alt text "Castle":
+ * Allows locating elements by their alt text.
+ *
+ * **Usage**
+ *
+ * For example, this method will find the image by alt text "Playwright logo":
*
* ```html
- * <img alt='Castle'>
+ * <img alt='Playwright logo'>
+ * ```
+ *
+ * ```js
+ * await page.getByAltText('Playwright logo').click();
* ```
*
* @param text Text to locate the element for.
@@ -16112,14 +16629,21 @@ export interface FrameLocator {
}): Locator;
/**
- * Allows locating input elements by the text of the associated label. For example, this method will find the input by
- * label text "Password" in the following DOM:
+ * Allows locating input elements by the text of the associated label.
+ *
+ * **Usage**
+ *
+ * For example, this method will find the input by label text "Password" in the following DOM:
*
* ```html
* <label for="password-input">Password:</label>
* <input id="password-input">
* ```
*
+ * ```js
+ * await page.getByLabel('Password').fill('secret');
+ * ```
+ *
* @param text Text to locate the element for.
* @param options
*/
@@ -16132,11 +16656,22 @@ export interface FrameLocator {
}): Locator;
/**
- * Allows locating input elements by the placeholder text. For example, this method will find the input by placeholder
- * "Country":
+ * Allows locating input elements by the placeholder text.
+ *
+ * **Usage**
+ *
+ * For example, consider the following DOM structure.
*
* ```html
- * <input placeholder="Country">
+ * <input type="email" placeholder="[email protected]" />
+ * ```
+ *
+ * You can fill the input after locating it by the placeholder text:
+ *
+ * ```js
+ * await page
+ * .getByPlaceholder("[email protected]")
+ * .fill("[email protected]");
* ```
*
* @param text Text to locate the element for.
@@ -16153,14 +16688,40 @@ export interface FrameLocator {
/**
* Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
* [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
- * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). Note that role selector **does not replace**
- * accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
- *
- * Note that many html elements have an implicitly
- * [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings) that is recognized by the role selector.
- * You can find all the [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines
- * **do not recommend** duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to
- * default values.
+ * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <h3>Sign up</h3>
+ * <label>
+ * <input type="checkbox" /> Subscribe
+ * </label>
+ * <br/>
+ * <button>Submit</button>
+ * ```
+ *
+ * You can locate each element by it's implicit role:
+ *
+ * ```js
+ * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
+ *
+ * await page.getByRole('checkbox', { name: 'Subscribe' }).check();
+ *
+ * await page.getByRole('button', { name: /submit/i }).click();
+ * ```
+ *
+ * **Details**
+ *
+ * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
+ * about the ARIA guidelines.
+ *
+ * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
+ * that is recognized by the role selector. You can find all the
+ * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
+ * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
* @param role Required aria role.
* @param options
*/
@@ -16233,7 +16794,25 @@ export interface FrameLocator {
}): Locator;
/**
- * Locate element by the test id. By default, the `data-testid` attribute is used as a test id. Use
+ * Locate element by the test id.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <button data-testid="directions">Itinéraire</button>
+ * ```
+ *
+ * You can locate the element by it's test id:
+ *
+ * ```js
+ * await page.getByTestId('directions').click();
+ * ```
+ *
+ * **Details**
+ *
+ * By default, the `data-testid` attribute is used as a test id. Use
* [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)
* to configure a different test id attribute if necessary.
*
@@ -16249,7 +16828,14 @@ export interface FrameLocator {
getByTestId(testId: string|RegExp): Locator;
/**
- * Allows locating elements that contain given text. Consider the following DOM structure:
+ * Allows locating elements that contain given text.
+ *
+ * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
+ * match by another criteria, like an accessible role, and then filter by the text content.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure:
*
* ```html
* <div>Hello <span>world</span></div>
@@ -16275,14 +16861,13 @@ export interface FrameLocator {
* page.getByText(/^hello$/i)
* ```
*
- * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
- * match by another criteria, like an accessible role, and then filter by the text content.
+ * **Details**
*
- * **NOTE** Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple
- * spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
+ * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
+ * one, turns line breaks into spaces and ignores leading and trailing whitespace.
*
- * **NOTE** Input elements of the type `button` and `submit` are matched by their `value` instead of the text content.
- * For example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
+ * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
+ * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
* @param text Text to locate the element for.
* @param options
*/
@@ -16295,11 +16880,20 @@ export interface FrameLocator {
}): Locator;
/**
- * Allows locating elements by their title. For example, this method will find the button by its title "Place the
- * order":
+ * Allows locating elements by their title attribute.
+ *
+ * **Usage**
+ *
+ * Consider the following DOM structure.
*
* ```html
- * <button title='Place the order'>Order Now</button>
+ * <span title='Issues count'>25 issues</span>
+ * ```
+ *
+ * You can check the issues count after locating it by the title text:
+ *
+ * ```js
+ * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
* ```
*
* @param text Text to locate the element for.