Skip to main content
Locator represents a view to elements that match a selector. Locators are strict by default and automatically wait for elements to be actionable.

Constructor

new Locator(frame: Frame, selector: string, options?: LocatorOptions)
frame
Frame
required
Parent frame
selector
string
required
Selector to locate elements
options
LocatorOptions
Locator options
  • hasText (string | RegExp): Matches elements containing text
  • hasNotText (string | RegExp): Matches elements not containing text
  • has (Locator): Matches elements containing another locator
  • hasNot (Locator): Matches elements not containing another locator
  • visible (boolean): Matches only visible elements

Filtering Methods

filter

Creates a filtered locator.
filter(options?: LocatorOptions): Locator
options
LocatorOptions
Filter options
Returns: Locator - Filtered locator

first

Returns first matching element.
first(): Locator
Returns: Locator - Locator for first element

last

Returns last matching element.
last(): Locator
Returns: Locator - Locator for last element

nth

Returns nth matching element.
nth(index: number): Locator
index
number
required
Element index (0-based, negative for reverse)
Returns: Locator - Locator for nth element

and

Combines with another locator (AND).
and(locator: Locator): Locator
locator
Locator
required
Locator to combine with
Returns: Locator - Combined locator

or

Combines with another locator (OR).
or(locator: Locator): Locator
locator
Locator
required
Locator to combine with
Returns: Locator - Combined locator

Chaining Methods

locator

Creates a descendant locator.
locator(selectorOrLocator: string | Locator, options?: LocatorOptions): Locator
selectorOrLocator
string | Locator
required
Descendant selector or locator
options
LocatorOptions
Locator options
Returns: Locator - Descendant locator

getByRole

Finds by ARIA role.
getByRole(role: string, options?: ByRoleOptions): Locator

getByText

Finds by text content.
getByText(text: string | RegExp, options?: { exact?: boolean }): Locator

getByLabel

Finds by label text.
getByLabel(text: string | RegExp, options?: { exact?: boolean }): Locator

getByPlaceholder

Finds by placeholder text.
getByPlaceholder(text: string | RegExp, options?: { exact?: boolean }): Locator

getByAltText

Finds by alt text.
getByAltText(text: string | RegExp, options?: { exact?: boolean }): Locator

getByTitle

Finds by title attribute.
getByTitle(text: string | RegExp, options?: { exact?: boolean }): Locator

getByTestId

Finds by test ID.
getByTestId(testId: string | RegExp): Locator

frameLocator

Creates a frame locator.
frameLocator(selector: string): FrameLocator

contentFrame

Gets frame content locator.
contentFrame(): FrameLocator
Returns: FrameLocator - Frame locator

Action Methods

click

Clicks the element.
click(options?: ClickOptions): Promise<void>
options
ClickOptions
Click options
  • button (‘left’ | ‘right’ | ‘middle’): Mouse button
  • clickCount (number): Number of clicks
  • delay (number): Delay between mousedown and mouseup
  • position (object): Click position
  • modifiers (string[]): Modifier keys
  • force (boolean): Force click
  • noWaitAfter (boolean): Don’t wait after click
  • timeout (number): Maximum time
Returns: Promise<void>

dblclick

Double clicks the element.
dblclick(options?: DblClickOptions): Promise<void>

fill

Fills an input element.
fill(value: string, options?: FillOptions): Promise<void>
value
string
required
Value to fill
options
FillOptions
Fill options
  • force (boolean): Force fill
  • noWaitAfter (boolean): Don’t wait after fill
  • timeout (number): Maximum time
Returns: Promise<void>

clear

Clears an input element.
clear(options?: FillOptions): Promise<void>
options
FillOptions
Clear options
Returns: Promise<void>

type

Types text into element.
type(text: string, options?: TypeOptions): Promise<void>
text
string
required
Text to type
options
TypeOptions
Type options
  • delay (number): Delay between key presses
  • timeout (number): Maximum time
Returns: Promise<void>

pressSequentially

Presses keys sequentially.
pressSequentially(text: string, options?: TypeOptions): Promise<void>

press

Presses a key.
press(key: string, options?: PressOptions): Promise<void>
key
string
required
Key to press (e.g., ‘Enter’, ‘ArrowDown’)
options
PressOptions
Press options
Returns: Promise<void>

check

Checks a checkbox.
check(options?: CheckOptions): Promise<void>

uncheck

Unchecks a checkbox.
uncheck(options?: CheckOptions): Promise<void>

setChecked

Sets checkbox state.
setChecked(checked: boolean, options?: CheckOptions): Promise<void>
checked
boolean
required
Whether to check or uncheck
options
CheckOptions
Check options
Returns: Promise<void>

selectOption

Selects options.
selectOption(values: string | string[] | SelectOption | SelectOption[], options?: SelectOptionOptions): Promise<string[]>
values
string | string[] | SelectOption | SelectOption[]
required
Values to select
options
SelectOptionOptions
Select options
Returns: Promise<string[]> - Selected values

hover

Hovers over element.
hover(options?: HoverOptions): Promise<void>

tap

Taps the element.
tap(options?: TapOptions): Promise<void>

focus

Focuses the element.
focus(options?: TimeoutOptions): Promise<void>

blur

Blurs the element.
blur(options?: TimeoutOptions): Promise<void>

dragTo

Drags to another locator.
dragTo(target: Locator, options?: DragAndDropOptions): Promise<void>
target
Locator
required
Target locator
options
DragAndDropOptions
Drag options
Returns: Promise<void>

setInputFiles

Sets input files.
setInputFiles(files: string | string[] | FilePayload | FilePayload[], options?: SetInputFilesOptions): Promise<void>
files
string | string[] | FilePayload | FilePayload[]
required
Files to upload
options
SetInputFilesOptions
Upload options
Returns: Promise<void>

dispatchEvent

Dispatches a DOM event.
dispatchEvent(type: string, eventInit?: any, options?: TimeoutOptions): Promise<void>
type
string
required
Event type
eventInit
any
Event initialization object
options
TimeoutOptions
Timeout options
Returns: Promise<void>

Content Methods

textContent

Returns text content.
textContent(options?: TimeoutOptions): Promise<string | null>
Returns: Promise<string | null> - Text content or null

innerText

Returns inner text.
innerText(options?: TimeoutOptions): Promise<string>
Returns: Promise<string> - Inner text

innerHTML

Returns inner HTML.
innerHTML(options?: TimeoutOptions): Promise<string>
Returns: Promise<string> - Inner HTML

inputValue

Returns input value.
inputValue(options?: TimeoutOptions): Promise<string>
Returns: Promise<string> - Input value

getAttribute

Returns attribute value.
getAttribute(name: string, options?: TimeoutOptions): Promise<string | null>
name
string
required
Attribute name
options
TimeoutOptions
Timeout options
Returns: Promise<string | null> - Attribute value or null

allTextContents

Returns all text contents.
allTextContents(): Promise<string[]>
Returns: Promise<string[]> - Array of text contents

allInnerTexts

Returns all inner texts.
allInnerTexts(): Promise<string[]>
Returns: Promise<string[]> - Array of inner texts

State Methods

isVisible

Checks if visible.
isVisible(options?: TimeoutOptions): Promise<boolean>
Returns: Promise<boolean> - True if visible

isHidden

Checks if hidden.
isHidden(options?: TimeoutOptions): Promise<boolean>
Returns: Promise<boolean> - True if hidden

isEnabled

Checks if enabled.
isEnabled(options?: TimeoutOptions): Promise<boolean>
Returns: Promise<boolean> - True if enabled

isDisabled

Checks if disabled.
isDisabled(options?: TimeoutOptions): Promise<boolean>
Returns: Promise<boolean> - True if disabled

isChecked

Checks if checked.
isChecked(options?: TimeoutOptions): Promise<boolean>
Returns: Promise<boolean> - True if checked

isEditable

Checks if editable.
isEditable(options?: TimeoutOptions): Promise<boolean>
Returns: Promise<boolean> - True if editable

Evaluation Methods

evaluate

Evaluates JavaScript on element.
evaluate<R, Arg>(pageFunction: Function, arg?: Arg, options?: TimeoutOptions): Promise<R>
pageFunction
Function
required
Function to evaluate
arg
any
Argument to pass
options
TimeoutOptions
Timeout options
Returns: Promise<R> - Evaluation result

evaluateAll

Evaluates on all matching elements.
evaluateAll<R, Arg>(pageFunction: Function, arg?: Arg): Promise<R>

evaluateHandle

Evaluates and returns JSHandle.
evaluateHandle<R, Arg>(pageFunction: Function, arg?: Arg, options?: TimeoutOptions): Promise<JSHandle<R>>

Utility Methods

count

Returns number of matching elements.
count(): Promise<number>
Returns: Promise<number> - Count of elements

all

Returns all matching locators.
all(): Promise<Locator[]>
Returns: Promise<Locator[]> - Array of locators

boundingBox

Returns bounding box.
boundingBox(options?: TimeoutOptions): Promise<Rect | null>
Returns: Promise<Rect | null> - Bounding box or null

screenshot

Takes a screenshot.
screenshot(options?: ScreenshotOptions): Promise<Buffer>
options
ScreenshotOptions
Screenshot options
  • path (string): File path to save to
  • type (‘png’ | ‘jpeg’): Image type
  • quality (number): JPEG quality
  • omitBackground (boolean): Transparent background
  • timeout (number): Maximum time
  • mask (Locator[]): Elements to mask
Returns: Promise<Buffer> - Screenshot buffer

scrollIntoViewIfNeeded

Scrolls element into view.
scrollIntoViewIfNeeded(options?: TimeoutOptions): Promise<void>
Returns: Promise<void>

selectText

Selects text.
selectText(options?: TimeoutOptions): Promise<void>
Returns: Promise<void>

waitFor

Waits for element state.
waitFor(options?: WaitForOptions): Promise<void>
options
WaitForOptions
Wait options
  • state (‘attached’ | ‘visible’ | ‘hidden’ | ‘detached’): Element state
  • timeout (number): Maximum time
Returns: Promise<void>

elementHandle

Returns element handle.
elementHandle(options?: TimeoutOptions): Promise<ElementHandle>
Returns: Promise<ElementHandle> - Element handle

elementHandles

Returns all element handles.
elementHandles(): Promise<ElementHandle[]>
Returns: Promise<ElementHandle[]> - Array of element handles

page

Returns parent page.
page(): Page
Returns: Page - Parent page

highlight

Highlights the element.
highlight(): Promise<void>
Returns: Promise<void>

ariaSnapshot

Returns ARIA snapshot.
ariaSnapshot(options?: TimeoutOptions): Promise<string>
Returns: Promise<string> - ARIA snapshot

describe

Adds custom description.
describe(description: string): Locator
description
string
required
Custom description
Returns: Locator - Locator with description

description

Returns custom description.
description(): string | null
Returns: string | null - Custom description or null

Usage Examples

Basic Locator Usage

import { test, expect } from '@playwright/test';

test('locator basics', async ({ page }) => {
  await page.goto('https://example.com');
  
  const button = page.locator('button#submit');
  await button.click();
  
  await expect(button).toBeDisabled();
});

Filtering Locators

const products = page.locator('.product');

// Filter by text
const macbook = products.filter({ hasText: 'MacBook' });
await macbook.click();

// Filter by child element
const inStock = products.filter({
  has: page.locator('.in-stock'),
});

// Chain filters
const filtered = products
  .filter({ hasText: 'iPhone' })
  .filter({ visible: true })
  .first();

Using Get By Methods

// By role
const submitButton = page.getByRole('button', { name: 'Submit' });
await submitButton.click();

// By text
const heading = page.getByText('Welcome back');
await expect(heading).toBeVisible();

// By label
const emailInput = page.getByLabel('Email address');
await emailInput.fill('[email protected]');

// By placeholder
const searchInput = page.getByPlaceholder('Search...');
await searchInput.type('Playwright');

// By test ID
const menu = page.getByTestId('main-menu');
await menu.click();

Chaining Locators

const article = page.locator('article');
const title = article.locator('h1');
const author = article.getByText(/Author:/i);

await expect(title).toContainText('Introduction');
await expect(author).toBeVisible();

Working with Multiple Elements

const items = page.locator('.item');

// Count elements
const count = await items.count();
console.log(`Found ${count} items`);

// Iterate over elements
for (let i = 0; i < count; i++) {
  const item = items.nth(i);
  console.log(await item.textContent());
}

// Get all locators
const allItems = await items.all();
for (const item of allItems) {
  await item.click();
}

// Get all text contents
const texts = await items.allTextContents();
console.log(texts);

Build docs developers (and LLMs) love