About this lesson
Selecting an element by id with page.locator() in Playwright
Learn Playwright JSBeginnerSelectors
How it works
page.locator('#value') describes an element using a CSS selector, and # followed by a name matches the element with that id. Creating a locator does not touch the page at all. Playwright only searches when you call a method on it, such as getAttribute(), click() or textContent(), and it waits for the element to appear before acting.
Locators are strict. If the selector matches more than one element when you act on it, Playwright throws a strict mode violation instead of quietly using the first match, which surfaces ambiguous selectors early.
About the assignment
On Text Fields, the last-name input has the id lastNameWithPlaceholder and grey hint text. You build a locator for it with a CSS id selector and read the hint from its placeholder attribute.
What you will do
- Create a locator with
page.locator()and a selector that starts with#. - Await
getAttribute()on that locator with the attribute nameplaceholder. - Log the value after the label
Placeholder:. - Add no extra wait: the locator waits for the field on its own.
Common mistakes
Awaiting page.locator()
page.locator()is synchronous and returns a locator immediately. Puttingawaitin front of it is harmless but suggests it searched the page, which it did not.Ids with special characters
An id such as
user.nameor1st-fieldis not a valid CSS id selector as written. Use the attribute form,[id="user.name"].Copying page.$() examples
Older tutorials use
page.$()and element handles. They do not auto-wait, so prefer locators.
In a real test suite
The Playwright team recommends user-facing locators such as getByRole('button', { name: 'Save' }) first, and stable ids or data-testid attributes when no accessible name fits. An id locator is still a sound choice when the id is stable.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://testkru.com/Elements/TextFields');
// TODO: Find element by ID "lastNameWithPlaceholder" using page.locator('#...')
// TODO: Get its "placeholder" attribute with getAttribute('placeholder')
// TODO: Print in format: "Placeholder: <value>"
await browser.close();
})();