Answer
Getting Text Content in Playwright
locator.textContent()
Returns the raw text content from the DOM — includes hidden text and whitespace.
const rawText = await page.locator('h1').textContent();
console.log(rawText); // " Welcome Home "
locator.innerText()
Returns the rendered, visible text — respects CSS display:none and visibility:hidden. Trims whitespace.
const visibleText = await page.locator('h1').innerText();
console.log(visibleText); // "Welcome Home"
locator.inputValue()
Gets the current value of an <input>, <textarea>, or <select> field.
const email = await page.getByLabel('Email').inputValue();
console.log(email); // "user@example.com"
const selectedOption = await page.getByLabel('Country').inputValue();
console.log(selectedOption); // "US"
locator.getAttribute()
Gets the value of a specific attribute.
const href = await page.getByRole('link', { name: 'About' }).getAttribute('href');
console.log(href); // "/about"
const placeholder = await page.getByLabel('Search').getAttribute('placeholder');
Comparison Table
| Method | What it Returns | Use Case |
|---|---|---|
textContent() | Raw DOM text (includes hidden) | Checking exact DOM text |
innerText() | Visible rendered text | Verifying user-visible text |
inputValue() | Input field value | Reading form field values |
getAttribute('x') | Attribute value | Href, src, data-* attrs |
Getting Text from Multiple Elements
// Get text from all list items
const items = await page.locator('li.product-name').allTextContents();
console.log(items); // ['Item 1', 'Item 2', 'Item 3']
// Get all inner texts
const texts = await page.locator('td.price').allInnerTexts();
console.log(texts); // ['$10.99', '$24.99', '$5.49']
Use in Assertions (Preferred Pattern)
Rather than reading text and asserting manually, use built-in matchers:
// Preferred — auto-retries until the text appears
await expect(page.locator('h1')).toHaveText('Welcome Home');
await expect(page.locator('h1')).toContainText('Welcome');
// Manual read (no auto-retry)
const text = await page.locator('h1').innerText();
expect(text).toBe('Welcome Home'); // No retry!
Best Practice: Use
expect(locator).toHaveText()for assertions (auto-retrying). UsetextContent()/innerText()only when you need the value for logic, not assertions.
