Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To store text from a page in a JavaScript variable, locate the element and await textContent() or innerText(): const text = await page.getByText('Welcome, John').textContent(); Use selectText() when you mean to highlight text in the browser; it performs a selection but does not return a string for your variable.

Read text into a variable, or select it in the browser?

These are two different operations that can sound alike. A locator identifies an element. From that locator, a text-reading method returns a string (or, for textContent(), potentially null) that you can assign to a variable. By contrast, selectText() focuses the matched element and selects its text in the page. It is useful for browser interaction, but it is not how you retrieve text for JavaScript logic.

const locator = page.getByText('Welcome, John');
const text = await locator.textContent(); // Read a value into your script
await locator.selectText();              // Select the text in the browser

Use one method or the other according to what you need next. For assertions, logging, transformation, or saving a value, read the text. For testing a user action that highlights text, use selectText().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a locator for the intended element

For non-interactive page text, Playwright’s getByText() is a direct option. Text matching can use a substring, an exact string, or a regular expression. Matching normalizes whitespace: repeated spaces are collapsed, line breaks are treated as spaces, and leading and trailing whitespace are ignored. If the target is interactive, prefer a locator reflecting its role and accessible name, such as getByRole(), rather than selecting it by incidental text or a brittle DOM path.

#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
const welcome = page.getByText('Welcome, John');
const heading = page.getByRole('heading', { name: 'Welcome' });

Locators are the central piece of Playwright’s auto-waiting and retry-ability, as Playwright’s locator guide describes. They let the script resolve the element when an operation is performed, rather than requiring you to keep a direct reference to a particular node. Prefer locators that match what a user sees over CSS or XPath chains that depend on the page’s internal structure.

Make the locator as specific as the page requires. A substring is convenient when surrounding text may vary, while exact text can help distinguish similar labels. A role-based locator is often clearer for a heading, button, or other interactive control. If a locator could match more than one element, narrow it before reading; otherwise the method may not represent the particular element you intended.

Pick the text-reading method that matches your goal

Need Method What you get
Text content of one matched DOM node textContent() The node’s DOM textContent, assigned from the awaited result.
Rendered text from one element innerText() The element’s rendered innerText, which can differ from its DOM text content.
Text from every matching element allTextContents() An array of each match’s text content.
Rendered text from every matching element allInnerTexts() An array of each match’s rendered text.
Current value of an input, textarea, or select inputValue() The form control’s current value, rather than ordinary page text.

Choose textContent() when the DOM text itself is what matters. Choose innerText() when you need the rendered-text representation. For example, a heading locator can read the visible heading text with innerText():

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const visibleHeading = await page
  .getByRole('heading', { name: 'Welcome' })
  .innerText();

Neither choice should be treated as a universal “better” method. They answer different questions about the matched element. If exact whitespace or hidden descendants matter to your use case, inspect the returned value with a representative page and choose the method whose semantics fit.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Run a minimal JavaScript example

The following complete Node.js script creates a page with known content, reads its heading into a variable, prints it, and then selects that heading in the browser. It assumes the playwright package is installed in the project.

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  try {
    const page = await browser.newPage();
    await page.setContent('<h1>Welcome, John</h1>');

    const heading = page.getByText('Welcome, John', { exact: true });
    const text = await heading.textContent();
    console.log(text);

    await heading.selectText();
  } finally {
    await browser.close();
  }
})();

The console receives the string read from the page. The final call highlights the heading in the browser; it does not change the value already stored in text. Remove that call if the script only needs to extract text.

Read collections without losing track of which result is which

If the page contains repeated items, use allTextContents() or allInnerTexts() to get an array. These methods are useful when every current match is relevant:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const itemTexts = await page.getByRole('listitem').allTextContents();
console.log(itemTexts);

The array order follows the matches returned by the locator. If your next step needs to pair each value with another field or act on a particular item, first make sure the locator describes the intended set. Do not use locator.all() as a substitute for waiting for a dynamic list: Playwright documents that all() immediately returns whatever matches at that moment, does not wait for matches to appear, and can be unpredictable while the list changes.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

For a changing page, identify a meaningful readiness condition before collecting values. A locator operation benefits from Playwright’s auto-waiting and retry-ability, but a collection snapshot taken before the desired items are present can still be incomplete. Use a locator operation that establishes the relevant element is available, then read the collection when the page is in the state your test or script requires.

Read form values with the control-specific method

An input’s typed value is not ordinary text content. Use inputValue() for an input, textarea, or select:

const value = await page.getByRole('textbox').inputValue();

This reads the control’s current value. Do not use textContent() to retrieve what a user typed into a form control. Likewise, fill() is for setting a value on an input, textarea, or contenteditable element; it is not a text-reading method.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const textbox = page.getByRole('textbox');
await textbox.fill('A value to enter');
const value = await textbox.inputValue();

Keeping reading and writing separate makes the code easier to reason about: fill() changes the page, while inputValue() reads the current control value.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle missing, changing, or ambiguous matches

The locator does not identify the expected text

Check the text as the page renders it and make the locator more precise. Whitespace normalization means a line break or repeated spaces do not necessarily need to appear exactly as in the source HTML. If the target is a heading, button, or other interactive element, consider a role locator with its name instead of a broad text match.

The page has not reached the state you want to read

Text on a dynamic page may not be present at the moment your code runs. Use a locator-based operation tied to the expected element and ensure your collection read happens after the content is available. Avoid assuming that all() waits for a list to populate; it does not.

You need visible wording, not DOM text

Switch from textContent() to innerText() when the rendered text is the intended result. The two represent different properties, so changing methods can change the returned value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You are reading a field and get the wrong kind of value

Use inputValue() for an input, textarea, or select. For a contenteditable element, use a text-reading method if you need its text; fill() can set its contents but does not return the current value.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

You expected selection to return a string

selectText() selects the element’s text in the browser. Store a returned string with textContent() or innerText(), and reserve selectText() for the actual selection interaction.

Keep extraction reliable and efficient

  • Use a stable locator. Text or role-based locators communicate intent better than selectors tied to incidental DOM nesting.
  • Read only the required representation. Use a single-element method for one value and a collection method when an array is the desired result.
  • Do not read too early. A locator helps with auto-waiting and retries, but your script still needs to target the page state relevant to the task.
  • Do not confuse DOM selection with data extraction. A highlighted selection is a browser action; a returned string is a value in your script.
  • Do not collect dynamic lists with an immediate snapshot by accident. The documented behavior of locator.all() makes it unsuitable as a wait-for-content operation.

The cost of this workflow is principally the browser work your script performs; the documentation cited for these methods does not establish a universal timing or performance figure. For a robust script, prefer a narrow locator and the method whose result you actually need rather than repeatedly collecting broad sets of page text.

Or skip the browser setup

If the goal is a clean visual record of a page rather than extracting its text into a JavaScript variable, ScreenshotNeo can return a screenshot or PDF from one GET request. It does not replace Playwright text extraction. For example, save a screenshot with cURL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.