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

In Playwright, “exists” can mean three different things: a node is attached to the DOM, a user can see it, or a locator matches a particular number of nodes. Use the assertion that matches your question:

await expect(locator).toBeAttached(); // connected to the DOM or a shadow root
await expect(locator).toBeVisible();   // attached and visible
await expect(locator).toHaveCount(1);  // exactly one matching node

These web-first assertions retry until the condition is met or the assertion timeout expires. That makes them safer for interfaces that render asynchronously than one-time state reads. See the LocatorAssertions API for the current assertion reference.

Choose the check that matches “exists”

What you need to know Playwright check What it proves
Is a node connected to the page? await expect(locator).toBeAttached() The locator resolves to an element attached to a Document or ShadowRoot.
Can a user see it? await expect(locator).toBeVisible() The node is attached, has a non-empty bounding box, and is not computed as visibility: hidden.
How many nodes match? await expect(locator).toHaveCount(n) Exactly n matching nodes exist.
What is the state right now for a branch? await locator.isVisible() or await locator.count() An immediate snapshot, without waiting for a later state.

A hidden element can be attached, so toBeAttached() may pass while toBeVisible() fails. Conversely, a broad locator may match several nodes even when one of them is visible. Decide whether your test is checking structure, user experience, or cardinality before writing the assertion.

Set up a locator that identifies the intended element

Assertions are only as useful as the locator they receive. Prefer user-facing contracts such as roles and accessible names, labels, text, placeholders, alt text, titles, or an explicit test ID. Playwright’s locator guidance recommends these strategies because they describe how a user or an accessibility tool identifies the control.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import { test, expect } from '@playwright/test';

test('save control is present', async ({ page }) => {
  await page.goto('https://example.com/settings');

  const saveButton = page.getByRole('button', { name: 'Save' });
  await expect(saveButton).toBeAttached();
});

Locators are resolved against the current DOM when you use them, which helps when a framework replaces nodes during a re-render. If an operation requires one target and your locator matches several, Playwright’s strictness will expose the ambiguity. Narrow the locator, or use .first(), .last(), or .nth(index) only when that choice is intentional.

Examples of precise locators

const status = page.getByRole('status');
const email = page.getByLabel('Email address');
const dialog = page.getByRole('dialog', { name: 'Confirm deletion' });
const card = page.getByTestId('profile-card');

A CSS selector can be appropriate for a stable implementation contract, but a selector such as div often says nothing about which element the test is meant to verify.

Check that an element is attached

Use toBeAttached() when “exists” means the element is connected to the document (or to a shadow root), regardless of whether it is currently displayed.

const toast = page.getByRole('status', { name: 'Saved' });
await expect(toast).toBeAttached();

This is useful for verifying that a component mounted, that a hidden dialog exists before it opens, or that a custom element was inserted. It does not establish that a user can interact with the node. A detached element, an absent component, or a locator that resolves to no node will fail after the assertion timeout.

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.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

When attachment is the right contract

  • Testing that a component rendered its required DOM structure.
  • Checking a hidden menu or dialog before a separate action reveals it.
  • Verifying an element inside an open shadow root.

Check that an element is visible

Use toBeVisible() when the user must be able to see the element. Playwright considers an element visible when it is attached, has a non-empty bounding box, and its computed visibility is not hidden. An element with display: none, an empty box, or an ancestor that prevents rendering does not satisfy the assertion. See Auto-waiting and actionability for the visibility definition and retry behavior.

const confirmation = page.getByRole('heading', { name: 'Order confirmed' });
await expect(confirmation).toBeVisible();

The assertion waits while the application is still rendering. It is generally preferable to adding a fixed delay such as page.waitForTimeout(1000), which can be either too short on a slow run or unnecessarily long on a fast one.

Attached but hidden

const panel = page.getByTestId('advanced-options');
await expect(panel).toBeAttached();
await expect(panel).not.toBeVisible();

This pair documents two different states: the panel exists in the DOM but is intentionally not shown. Use the negative visibility assertion only when hidden state is part of the behavior you want to protect.

Check how many matching elements exist

Use toHaveCount(n) for cardinality. It retries until the locator matches the exact number or the timeout expires.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
const rows = page.getByRole('row');
await expect(rows).toHaveCount(5);

For an exact-one contract:

const submit = page.getByRole('button', { name: 'Submit' });
await expect(submit).toHaveCount(1);

Do not use an exact-one assertion merely because one match happens to be convenient today. If duplicate controls are valid on different cards, scope the locator to the relevant card or assert the documented count. To test that at least one match eventually appears, a visibility assertion on the intended visible match is often clearer; if visibility is irrelevant, choose and document the count your component permits.

Immediate readings versus retrying assertions

locator.isVisible() and locator.count() return the state at the instant they run. They are useful for deliberate conditional logic, but they do not wait for a component that will appear a moment later.

const saveButton = page.getByRole('button', { name: 'Save' });

// Immediate snapshot; suitable when branching on the current state.
const visibleNow = await saveButton.isVisible();
const matchesNow = await saveButton.count();

if (visibleNow) {
  await saveButton.click();
}

If the page is still updating, use a web-first assertion instead:

await expect(saveButton).toBeVisible();
await expect(saveButton).toHaveCount(1);

The Locator API documents these immediate methods, while Playwright’s best practices explain why waiting assertions reduce timing flakiness.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Use the right timeout

Assertions use Playwright’s configured expect timeout. Keep the default when the application normally settles quickly; increase it for a known slow operation rather than inserting arbitrary sleeps.

await expect(page.getByRole('status')).toBeVisible({ timeout: 10_000 });

A longer timeout cannot fix a locator that never matches. First confirm the page URL, frame, accessible name, and selector. Set a project-wide value only when the whole application has a consistent startup characteristic.

Frames, shadow DOM, and dynamic interfaces

Elements inside an iframe

A locator created from the main page does not cross into an iframe. Enter the frame first:

const paymentFrame = page.frameLocator('iframe[title="Payment"]');
await expect(paymentFrame.getByLabel('Card number')).toBeAttached();

Shadow DOM

Playwright locators can pierce open shadow DOM. toBeAttached() still means connection to a document or shadow root; a closed shadow root requires an application-supported test contract because outside selectors cannot inspect its internals.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Re-rendering and stale references

Prefer a Locator over an ElementHandle for assertions. A locator resolves the current matching node when used, so it remains suitable when a framework unmounts and mounts a replacement element.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failures and fixes

Symptom Likely cause Fix
toBeAttached times out The element never mounted, the page is wrong, or the locator is too broad or incorrect. Check page.url(), inspect the locator in trace/UI mode, and use a stable role, label, or test ID.
toBeVisible fails but attachment passes The node is hidden, has no layout box, or is covered by application state that prevents rendering. Assert the intended state, open the component first, or use toBeAttached if visibility is not required.
Strict-mode violation The locator matches multiple nodes for an operation requiring one. Scope it to a card, dialog, or section; use .nth() only when ordering is a real contract.
isVisible() returns false intermittently It was sampled before asynchronous rendering completed. Replace the immediate read with await expect(locator).toBeVisible().
count() is occasionally zero The list is populated after the count call. Use toHaveCount(expected) with an appropriate timeout.
Locator works on the page but not in a frame The target is inside an iframe. Use frameLocator() or obtain the correct frame before locating.

A complete test that distinguishes all three meanings

import { test, expect } from '@playwright/test';

test('notification lifecycle', async ({ page }) => {
  await page.goto('https://example.com/dashboard');

  const notification = page.getByRole('status');

  // The component is mounted, even if its initial state is hidden.
  await expect(notification).toBeAttached();

  await page.getByRole('button', { name: 'Show notification' }).click();

  // Rendering is asynchronous, so wait for the user-visible state.
  await expect(notification).toBeVisible();

  // The application contract says there is one status region.
  await expect(notification).toHaveCount(1);
});

Or skip the browser setup

If your goal is to obtain a clean image of a page rather than test an element’s state, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF; it accepts cookie banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status.

Using cURL (see the ScreenshotNeo documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. It supports full-page and element captures, device presets, custom CSS and JavaScript, waits, request blocking, authentication headers and cookies, geolocation, caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, and a usage API. Every feature is on every plan: 1,000 screenshots per month are free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Practical decision checklist

  • Use toBeAttached() for DOM or shadow-root presence.
  • Use toBeVisible() for a user-visible outcome.
  • Use toHaveCount(n) for an exact number of matches.
  • Use isVisible() or count() only when an immediate snapshot is intentional.
  • Build the locator from a stable, user-facing contract and scope it to the correct frame or component.
  • Let assertions retry instead of masking races with fixed delays.

Frequently Asked Questions

Can I use locator.exists() in Playwright?

Playwright does not use a single exists() assertion. Choose toBeAttached(), toBeVisible(), or toHaveCount() according to the state you need to prove.

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

Should I assert visibility or attachment for a hidden dialog?

Assert attachment when the requirement is that the dialog is mounted. Assert visibility after the action that should open it.

How do I check for at least one matching element?

Use a locator that identifies the intended visible match and assert toBeVisible(), or assert the documented minimum/expected count with toHaveCount().

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.