</>

Technology

Playwright

Difficulty

Beginner

Interview Question

How do you get text content of an element in Playwright?

Answer

Getting Text Content in Playwright

locator.textContent()

Returns the raw text content from the DOM — includes hidden text and whitespace.

TypeScript
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.

TypeScript
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.

TypeScript
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.

TypeScript
const href = await page.getByRole('link', { name: 'About' }).getAttribute('href');
console.log(href); // "/about"

const placeholder = await page.getByLabel('Search').getAttribute('placeholder');

Comparison Table

MethodWhat it ReturnsUse Case
textContent()Raw DOM text (includes hidden)Checking exact DOM text
innerText()Visible rendered textVerifying user-visible text
inputValue()Input field valueReading form field values
getAttribute('x')Attribute valueHref, src, data-* attrs

Getting Text from Multiple Elements

TypeScript
// 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:

TypeScript
// 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). Use textContent() / innerText() only when you need the value for logic, not assertions.

Follow AutomateQA

Related Topics