Skip to main content

Playwright Locators in JavaScript (Complete Guide)

๐ŸŽฏ Playwright Locators in JavaScript (Complete Guide)

This guide explains each Playwright locator with:

  • ✅ What it is
  • ๐Ÿ• When to use
  • ⚙️ How to use it
  • ๐ŸŽฏ Benefits
  • ๐Ÿงช Code Examples

๐Ÿ”น 1. Locator by ID

  • ✅ What: Selects an element with a unique id.
  • ๐Ÿ• When: Element has a unique id.
  • ⚙️ How: page.locator('#username')
  • ๐ŸŽฏ Benefit: Fast and reliable.
<input id="username" />

await page.locator('#username').fill('John');

๐Ÿ”น 2. Locator by Class

  • ✅ What: Selects by class.
  • ๐Ÿ• When: Repeated or styled elements.
  • ⚙️ How: page.locator('.password')
  • ๐ŸŽฏ Benefit: Useful for shared styling.
<input class="password" />

await page.locator('.password').fill('12345');

๐Ÿ”น 3. Locator by Text

  • ✅ What: Matches visible element text.
  • ๐Ÿ• When: For buttons, links, etc.
  • ⚙️ How: page.getByText('Login')
  • ๐ŸŽฏ Benefit: Human-readable.
<button>Login</button>

await page.getByText('Login').click();

๐Ÿ”น 4. Locator by Placeholder

  • ✅ What: Uses placeholder text.
  • ๐Ÿ• When: For form hints.
  • ⚙️ How: getByPlaceholder()
  • ๐ŸŽฏ Benefit: Clear and targeted.
<input placeholder="Enter username" />

await page.getByPlaceholder('Enter username').fill('admin');

๐Ÿ”น 5. Locator by Role

  • ✅ What: Uses ARIA roles (e.g., button, heading).
  • ๐Ÿ• When: For accessible apps.
  • ⚙️ How: getByRole()
  • ๐ŸŽฏ Benefit: Accessibility-friendly.
<button>Login</button>

await page.getByRole('button', { name: 'Login' }).click();

๐Ÿ”น 6. Locator by Label

  • ✅ What: Uses label text for inputs.
  • ๐Ÿ• When: For labeled form fields.
  • ⚙️ How: getByLabel()
  • ๐ŸŽฏ Benefit: Strong for forms.
<label for="user">Username</label>
<input id="user" />

await page.getByLabel('Username').fill('john');

๐Ÿ”น 7. Locator by Name Attribute

  • ✅ What: Targets elements with name.
  • ๐Ÿ• When: Useful for forms.
  • ⚙️ How: locator('[name="email"]')
  • ๐ŸŽฏ Benefit: Common in backend forms.
<input name="email" />

await page.locator('[name="email"]').fill('abc@example.com');

๐Ÿ”น 8. Locator by Data Test ID

  • ✅ What: Uses data-testid.
  • ๐Ÿ• When: For stable test targeting.
  • ⚙️ How: locator('[data-testid="xyz"]')
  • ๐ŸŽฏ Benefit: Doesn’t break on UI changes.
<button data-testid="login-button">Login</button>

await page.locator('[data-testid="login-button"]').click();

๐Ÿ”น 9. Locator by Tag + Class

  • ✅ What: Combines element tag and class.
  • ๐Ÿ• When: For reusable component patterns.
  • ⚙️ How: locator('li.item')
  • ๐ŸŽฏ Benefit: Precise targeting in groups.
<li class="item">Item 1</li>

await page.locator('li.item').click();

๐Ÿ”น 10. Locator with nth(), first(), last()

  • ✅ What: Picks from multiple matches.
  • ๐Ÿ• When: Lists, repeated buttons, etc.
  • ⚙️ How: nth(index), first(), last()
  • ๐ŸŽฏ Benefit: Fine control on lists.
<ul>
  <li class="item">One</li>
  <li class="item">Two</li>
</ul>

await page.locator('li.item').nth(1).click();

✅ Best Practices

Practice Why
Use data-testid Most stable and intention-specific
Prefer getByRole or getByLabel Ensures accessibility
Avoid excessive use of nth() Breaks if DOM order changes
Use text-based locators for user-facing elements Reflects real user interaction

Need help converting this to a GitHub test project or video tutorial? Let me know!

Comments

Popular posts from this blog

Step-by-Step: Launch Browser, Context, and Page in Playwright and Run Test and Configuration (JavaScript)

๐ŸŽฅ Setup Browser, Context, Page & Run Config Test Scripts with package.json & playwright.config.js Step-by-Step: Launch Browser, Context, and Page in Playwright and Run Test and Configuration (JavaScript) 1. Install Playwright You can install Playwright using the following command: npm init playwright@latest 2. Create a Basic Test Script Understand the core Playwright architecture: Element Description browser Controls the browser instance (like Chrome, Firefox, etc.) context Acts like a separate browser profile (cookies, localStorage are isolated) page A single browser tab where interaction happens 3. Run the Test npx playwright test example.spec.js Ways to Run TypeScript Tests Way Command Notes ๐ŸŸข Via npx npx playwright test Uses built-in TypeScript support ๐ŸŸข With s...

Playwright Test Structure in Details -Session-02

๐ŸŽฅ Playwright: test.only, Hooks & Grouping with test.describe Explained Let’s go step-by-step , showing how to build from a single test , to using beforeEach / afterEach , and then organizing things with test.describe . ✅ Step 1: Basic Single Test with test.only import { test, expect } from '@playwright/test' ; test. only ( '๐Ÿš€ Basic test - check title' , async ({ page }) => { await page. goto ( 'https://example.com' ); await expect (page). toHaveTitle ( /Example Domain/ ); }); test.only ensures only this test runs — great for debugging. ✅ Step 2: Add beforeEach and afterEach import { test, expect } from '@playwright/test' ; test. beforeEach ( async ({ page }) => { console . log ( '๐Ÿ”„ Setting up before each test' ); await page. goto ( 'https://example.com' ); }); test. afterEach ( async ({ page }, testInfo) => { console . log ( `๐Ÿ“ฆ Finished test: ${testInfo.title} `); }); test. only ( ...