Answer
textContent() vs innerText() in Playwright
Both methods return the text of an element but differ in what they include.
locator.textContent()
Returns the raw text content from the DOM — exactly what the browser stores in the text nodes, including:
- ✓Text from hidden elements (
display:none) - ✓Script/style tag content (if directly targeted)
- ✓All whitespace exactly as in the HTML
TypeScript
const text = await page.locator('#my-element').textContent();
// May return: " Hello World " (with extra spaces)
// Returns text from hidden children too
locator.innerText()
Returns the rendered, visible text — what the user actually sees on screen:
- ✓Ignores elements with
display:noneorvisibility:hidden - ✓Trims leading/trailing whitespace
- ✓Respects CSS
text-transform(uppercase/lowercase) - ✓Processes
<br>as newlines
TypeScript
const text = await page.locator('#my-element').innerText();
// Returns: "Hello World" (trimmed, no hidden text)
Example Comparison
HTML:
HTML
<div id="product">
<span>Available</span>
<span style="display:none">Out of Stock</span>
</div>
TypeScript
const rawText = await page.locator('#product').textContent();
// "Available Out of Stock" ← includes hidden span
const visibleText = await page.locator('#product').innerText();
// "Available" ← only visible text
Summary Table
textContent() | innerText() | |
|---|---|---|
| Includes hidden | Yes | No |
| Whitespace | Raw | Normalized |
| Performance | Faster (no reflow) | Slower (requires reflow) |
| CSS text-transform | Ignored | Applied |
| Newlines from br | No | Yes |
When to Use Each
TypeScript
// Use textContent() when you need raw DOM text
// including potentially hidden content
const raw = await page.locator('.data-value').textContent();
// Use innerText() when you want what the user sees
const visible = await page.locator('.status-text').innerText();
// For assertions, use toHaveText() — it works like innerText()
await expect(page.locator('.status')).toHaveText('Available');
For most tests, use
expect(locator).toHaveText()— it uses visible text (likeinnerText()) and auto-retries. UsetextContent()/innerText()only when you need the raw string value.
