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

A TestCafe selector is an asynchronous query for elements in the page’s DOM. Start with a CSS selector or a client-side function, refine the result with attributes, text, or traversal methods, then pass it to an action or assertion. Make the query specific enough to identify the intended element: when multiple elements match, TestCafe uses the first one.

How TestCafe selectors work

Selectors locate elements; TestCafe actions such as click and typeText interact with them. You can create a Selector object and pass it to an action or assertion. For simple targets, a CSS selector string can also be used directly as an action target. See the official Element Selectors guide and Selector Object reference.

A selector variable holds a query, not a frozen snapshot of the page. When the query is used, TestCafe evaluates it against the DOM, so repeated use can find different elements if earlier actions changed the page.

Choose a selector that can survive page changes

Prefer a stable identifier that expresses the element’s purpose. The TestCafe guide recommends custom attributes such as data-test-id because they can remain independent of visual design and layout. Confirm that the application actually renders the attribute and that it identifies the intended target.

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.
Selector approach Use it when Trade-off
CSS selector A stable ID, custom attribute, tag, or CSS relationship directly describes the target. Familiar and concise; selectors that depend on mutable classes or deep layout relationships may be brittle.
Function-based selector Client-side DOM inspection or page state is needed to derive the target. Flexible, but the function must comply with TestCafe’s documented serialization restrictions; for example, it cannot use async/await or generators.
Selector-based query and methods An existing query needs filtering or traversal to a related element. Methods can express relationships without one long CSS path, but you should still verify the final match.

These initialization styles are documented in the Selector constructor reference. Framework-specific selector integrations are available through additional libraries; do not assume that a base CSS query identifies framework components.

Build and use a selector

This example uses an application-provided test attribute and passes the selector to a click action:

import { Selector } from 'testcafe';

const submit = Selector('[data-test-id="submit"]');

fixture`Checkout`
    .page`https://example.com/checkout`;

test('submit checkout', async t => {
    await t.click(submit);
});

The example assumes the checkout page has exactly the intended element with that attribute. If it does not, refine the query rather than assuming a broad selector is safe.

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.

Combine an element type with an attribute

Use withAttribute to require both a tag and an attribute value:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const submit = Selector('button').withAttribute('data-test-id', 'submit');

withAttribute accepts an attribute name and an optional value. String arguments require strict matches; regular expressions are also supported. See withAttribute().

Find a descendant

Start at a stable parent, then use find to select a matching descendant. It accepts a CSS selector or a filter function:

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 checkout = Selector('form').withAttribute('data-test-id', 'checkout');
const email = checkout.find('input[type="email"]');

This expresses the intent “the email input inside the checkout form” without relying on a long page-wide CSS path. Reference: find().

Match text carefully

withText matches a case-sensitive string contained in text content, or a regular expression. withExactText requires an exact, case-sensitive text match:

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 continueButton = Selector('button').withExactText('Continue');

Text inside a child can also cause an ancestor to match. If that makes the result ambiguous, constrain the tag, add an attribute, or start from a more specific parent. References: withText() and withExactText().

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

Traverse or narrow a query

Selector methods such as parent, child, find, withAttribute, withText, and nth let you traverse or refine a query. Prefer a meaningful relationship or stable attribute over selecting an arbitrary position. Use nth only when position is itself part of the test’s intent and the page structure makes that position reliable.

Check matches before relying on them

TestCafe’s documented behavior is to use the first matching element for a page action or assertion when a selector matches several DOM elements. A broad selector can therefore succeed while operating on the wrong match. Use count or exists when the test needs to inspect whether a query matched, and make the action’s target as specific as practical. The Element Selectors guide states: “If a page action / assertion Selector matches multiple DOM elements, TestCafe performs the action / assertion with the first matching element.”

Understand waiting and visibility

For action targets, TestCafe automatically waits for the selector to appear and become visible, up to the selector timeout. By contrast, exists and count are calculated immediately; the selector timeout does not change those checks. Assertions have a separate assertion timeout.

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.

TestCafe does not interact with elements it classifies as invisible. Its documented criteria include display: none, visibility: hidden or collapse, and zero width or height on the element or an ancestor. Opacity, z-index, and page position are not part of that stated visibility classification. This classification is not a guarantee that a person can see or reach the element. For a selector-based visibility filter, see filterVisible().

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

Handle Shadow DOM and pseudo-elements

Pseudo-elements such as ::before and ::after are not action targets. For Shadow DOM, first locate the shadow root, then use selector methods to traverse into it. The shadow-root result is an entry point, not itself a valid target for an action or assertion. See the Selector constructor documentation for documented selector behavior and restrictions.

Troubleshoot selector failures

  • The action fails because no target appears: Check that the page rendered the expected element and attribute, that the selector is scoped to the correct container, and that the element becomes available before the selector timeout expires.
  • The action affects the wrong matching element: The query is broader than intended. Add a stable attribute, constrain the element type, use a parent query with find, or otherwise refine it; do not rely on the first match accidentally being correct.
  • exists or count reports no match even though the page changes later: These checks are immediate rather than waiting for the selector timeout. Use an assertion with its assertion timeout when the test needs to wait for a condition.
  • A target seems visible but TestCafe will not interact with it: Check the element and its ancestors for hidden display or visibility settings and zero dimensions. Opacity or stacking order does not change the documented visibility classification.
  • A text selector matches an ancestor as well as the control: Text in a descendant can contribute to an ancestor’s match. Add a tag or attribute constraint, or locate the control relative to a more specific parent.
  • A Shadow DOM query cannot be clicked directly: Traverse from the shadow-root entry point to the actual element. Do not pass the root itself as the action or assertion target.
  • A client-side selector function is rejected: Review the constructor restrictions and remove unsupported constructs such as async/await or generators from the function.

Or skip the browser setup

TestCafe selectors are for finding and interacting with elements in browser tests. If your task is instead to capture a page as an image or PDF, ScreenshotNeo is a separate website screenshot API and MCP server—not a replacement for TestCafe actions or assertions. One GET request can return a screenshot or PDF:

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 and consent banners are accepted and removed before capture, along with supported newsletter popups and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and responses report the page verdict and billing status. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.

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

FAQ

Can I use a CSS string directly in an action?

Yes. A simple CSS selector string can be used directly as an action target; use a Selector object when you need to compose or refine the query.

Does TestCafe selector visibility mean a person can see the element?

Not necessarily. TestCafe’s documented classification checks display, visibility, and dimensions; factors such as opacity, z-index, and page position do not affect that stated check.

Do I need an additional library to select framework components?

Framework-specific selector integrations are available through additional libraries. The base CSS selector does not, by itself, imply framework-component lookup.

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.

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