October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Find an Element in Puppeteer

Use Puppeteer locators for element interactions, immediate query methods for existing matches, and waitForSelector when you need an explicit wait.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For most current Puppeteer code, use page.locator(selector) when you want to find an element and act on it. Use page.$() or page.$$() for immediate queries, and page.waitForSelector() when you need an explicit wait for an element to appear. Puppeteer recommends locators for selecting elements and interacting with them.

Choose a Puppeteer method for the job

Goal Method What happens
Find an element and interact with it page.locator(selector) Recommended interaction API. Locator actions wait for action preconditions and retry when the target is not ready.
Query the first match that exists now page.$(selector) Returns an element handle or null if no match is found.
Query all matches that exist now page.$$(selector) Returns an array of element handles, which may be empty.
Wait explicitly for a match or visibility page.waitForSelector(selector, options) Waits for a selector state and returns an element handle or throws on timeout.
Read or transform one match page.$eval(selector, fn) Runs a function on the first matching element; throws if there is no match.
Read or transform all matches page.$$eval(selector, fn) Runs a function on the matching elements as a group.

These methods and behaviors are documented in Puppeteer’s Page interactions guide and the waitForSelector API reference.

As an Amazon Associate I earn from qualifying purchases.

Pick a selector that identifies the element

CSS selectors work directly in Puppeteer selector APIs. Prefer a meaningful ID, name, data attribute, or other durable attribute when the page provides one. Avoid relying on generated class names or long absolute XPath expressions when a more readable selector is available.

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

CSS selector

const submit = page.locator('button.submit');
await submit.click();

Text selector

Puppeteer supports text selectors. This example selects text matching “Save changes”:

const save = page.locator('::-p-text(Save changes)');
await save.click();

Accessibility role and name

ARIA selectors use the browser’s computed accessible role and name:

const save = page.locator('::-p-aria([name="Save changes"][role="button"])');
await save.click();

XPath and shadow DOM

XPath selectors use the browser’s native Document.evaluate. Puppeteer also provides selector syntax for traversing open shadow roots; consult its selector guide for exact syntax and escaping rules, especially when selector text contains punctuation.

const submit = page.locator('::-p-xpath(//button[@type="submit"])');
await submit.click();

Find an element and interact with it using a locator

A locator describes how to find an element; actions such as click() and fill() perform the interaction. Locator actions check readiness conditions, including visibility and enabled state where relevant, viewport placement, and a stable bounding box for actions such as clicking or filling. This is useful when rendering or layout is still changing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.locator('button.submit').click();

const email = page.locator('input[name="email"]');
await email.fill('[email protected]');

The locator action is usually preferable to querying an element handle and then acting on it when the page may still be changing. It does not guarantee that your selector is unique: ensure it describes the intended target.

Query elements that are already present

Get the first match

page.$() performs an immediate lookup. It does not wait for future rendering, so check for null before using the result.

const button = await page.$('button.submit');
if (button) {
  await button.click();
  await button.dispose();
}

Get every match

page.$$() returns all matches present at query time. The result can be empty.

const items = await page.$$('li');
for (const item of items) {
  console.log(await item.evaluate(el => el.textContent?.trim()));
  await item.dispose();
}

Read one element with $eval()

Use $eval() to run a function on the first matching element in the page context. It throws if the selector matches nothing.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const value = await page.$eval(
  'input[name="email"]',
  el => el.value
);

In TypeScript, give the element a specific type when accessing element-specific properties such as an input’s value, for example HTMLInputElement.

Read or transform multiple matches with $$eval()

const labels = await page.$$eval(
  'li',
  items => items.map(item => item.textContent?.trim())
);

Wait for a dynamic element

Use page.waitForSelector() when you need to wait for a selector to enter the DOM or reach a requested visibility state. Its documented default timeout is 30,000 milliseconds; page default-timeout settings can change that. The method supports visible, hidden, timeout, and cancellation signal options.

const result = await page.waitForSelector('.result-card', {
  visible: true,
  timeout: 10_000,
});

if (result) {
  await result.click();
  await result.dispose();
}

waitForSelector() returns an element handle. Unlike a locator action, it does not automatically retry a later action if the element becomes unready after the wait. Dispose of the handle when you are finished with it. If your goal is simply to act on the element, prefer a locator and let its action handle readiness.

Read values or HTML in the page context

The function passed to $eval() or $$eval() runs in the page context. You can also pass an element handle to page.evaluate(); Puppeteer waits for a returned promise to resolve.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const heading = await page.$eval(
  'h1',
  element => element.textContent?.trim()
);

const body = await page.$('body');
if (body) {
  const html = await page.evaluate(element => element.innerHTML, body);
  await body.dispose();
}

Troubleshoot common lookup problems

  • The query returns null or an empty array: $() and $$() only inspect the DOM at the time of the call. If content is rendered later, use a locator action or wait explicitly with waitForSelector().
  • $eval() throws: no element matched when the query ran. Check the selector, or use $() and handle null if absence is expected.
  • The wait times out: confirm the selector matches the actual DOM and that the requested state is possible. A wait for visible: true will not succeed merely because a matching node exists but is not visible.
  • The wrong matching element is used: $() and $eval() operate on the first match. Make the selector more specific, or use $$()/$$eval() when you need to inspect all matches.
  • A handle is no longer needed: dispose element handles returned by $(), $$(), or waitForSelector() after use.
  • Text selector syntax fails: text and other custom selectors have Puppeteer-specific syntax and escaping rules. Check the current page interactions guide for selector punctuation and shadow-root details.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a page rather than automate a browser interaction, ScreenshotNeo can return a screenshot or PDF with one GET request. For example, with cURL:

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 parameters. Before the shot, it accepts cookie/consent banners and removes 60+ known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers say which verdict applied and whether it was billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for 1,000 free screenshots a month, with no card required.

Frequently Asked Questions

Does Puppeteer’s $() wait for an element to appear?

No. It checks for a match at the time it runs and returns null when there is none.

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

What does Puppeteer’s waitForSelector() return?

It returns an element handle when the selector reaches the requested condition; it throws if the wait times out.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.