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.

Use a CSS selector to identify a page element by its tag, ID, class, attributes, state, or position in the DOM. In a browser test, start with a short selector based on stable markup, scope it to a meaningful container when needed, and verify that it matches the intended element. If the test is about what a person can perceive—such as a button’s role—consider a role locator instead.

What a CSS selector does

A CSS selector is a pattern matched against elements in a document tree. The W3C defines a selector as “a boolean predicate that takes an element in a tree structure and tests whether the element matches the selector or not” in its Selectors Level 4 Working Draft dated 22 January 2026. A selector matches DOM elements, not visual coordinates on the screen.

Selectors can express conditions on an element and relationships between elements. For example, button.primary matches a button that also has the primary class. By contrast, a comma-separated selector list such as button, a matches elements that satisfy either selector. MDN’s CSS selectors reference describes the common syntax and selector-list behavior.

Common CSS selector syntax

Selector type Example What it matches
Type button Elements with the button tag.
ID #save The element with the ID save.
Class .primary Elements with the primary class.
Attribute [aria-label="Save"] Elements whose aria-label attribute equals Save.
Compound button.primary A button element that also has the primary class.
Descendant form input An input anywhere inside a form.
Child form > input An input that is a direct child of a form.
Pseudo-class input:checked An input in the checked state.
Position li:nth-child(2) A list item that occupies the second child position of its parent.

Use a comma when any one of several patterns is acceptable. Use multiple simple selectors without a combinator when the same element must satisfy every condition: .foo.bar means one element has both classes, not an element with class foo containing another with class bar. A space expresses a descendant relationship; > expresses a direct-parent relationship.

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.

A practical workflow for finding an element

  1. Inspect the rendered DOM. Identify the actual element and its attributes in the state where the test will run. Do not assume a sample selector fits markup you have not inspected.
  2. Choose a short, meaningful condition. Prefer a stable ID, name, accessible attribute, or an explicit test ID that the application maintains as an automation contract. For example, button[data-testid="save"] targets a button with that test ID.
  3. Scope repeated controls to their context. If a page has multiple email fields, a selector such as form#checkout input[name="email"] identifies the email input inside the checkout form rather than relying on page-wide uniqueness.
  4. Check what it resolves to. Confirm that the selector identifies the intended element in the current page state. If multiple matches are expected, make the distinction explicit rather than silently relying on their order.
  5. Match the locator to the test’s intent. If the test should interact with a control as a user perceives it, consider a role locator. If the application defines a deliberate test-ID contract, use that contract rather than incidental markup.

Using CSS selectors in Playwright

Playwright supports CSS locators, including page.locator('button'). These illustrative examples show the syntax; they are not reports of tests run on a live site:

// Click a button identified by an explicit test ID
await page.locator('button[data-testid="save"]').click();

// Fill the email field scoped to a form with a stable ID
await page.locator('form#checkout input[name="email"]').fill('reader@example.com');

For a test that is meant to address a button by its user-facing role, a role locator may communicate that intent more directly. Playwright’s locator documentation supports CSS locators but cautions that CSS and XPath tied to the DOM can be less resilient when that DOM changes; it recommends considering role locators or an explicit testing contract such as test IDs. This is guidance for Playwright, not a universal ban on CSS selectors.

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.

How to choose between CSS, role, and test-ID locators

Question CSS selector is a fit when… Consider another locator when…
What should the test express? The target is naturally defined by stable DOM attributes or a short relationship. The test should address the control by the role or name a user perceives.
What does the selector depend on? It uses durable, meaningful attributes and a clear local context. It relies on generated classes, deep ancestry, or incidental sibling order.
Does the app provide a testing hook? A deliberate test ID is available and a CSS locator is appropriate to the framework. The team wants to make the test-ID contract explicit through the framework’s dedicated locator.
Is the target unique? The selector identifies the intended element in a meaningful scope. It matches several elements and the test is depending on an accidental first or last match.

A stable, short CSS selector can be a good choice. A generated chain with many ancestors and :nth-child() steps is more exposed to changes in page structure. Keep positional selectors for cases where position itself is what the test needs to verify.

Why CSS selectors break—and how to make them more resilient

A selector becomes fragile when it describes incidental implementation details rather than a stable target. A redesign or markup refactor can change nesting, classes, or sibling order without changing what the user sees. A long chain of ancestor relationships or positional steps can therefore stop matching—or match a different element—after an otherwise ordinary page change.

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.
  • Prefer short selectors tied to attributes the application intends to keep stable.
  • Scope a repeated control to a meaningful container instead of building a long path from the document root.
  • Avoid generated class names and positional selectors unless the test specifically depends on them.
  • Use a role locator when the test’s intent is the user-facing role; use an explicit test ID when the application promises that hook for tests.
  • When a selector fails, inspect the current DOM and matching elements before changing it. The failure may reflect a changed page state or markup, not merely a syntax error.

Common selector problems

Symptom Likely cause What to do
No element matches The rendered markup differs from the assumed tag, attribute, relationship, or page state. Inspect the DOM at the point the test runs; revise the selector to reflect the actual stable markup.
More than one element matches The condition is too broad or is not scoped to a unique region. Add a meaningful container or stable attribute. Do not depend on incidental match order.
The test breaks after a redesign The selector depends on changed nesting, generated classes, or sibling positions. Replace structural details with a stable attribute, an explicit test ID, or a role locator that represents the test’s intent.
A comma-separated selector seems too broad A selector list matches any listed pattern. Use a compound selector when all conditions must apply to the same element, or narrow each alternative.
A child selector misses a nested element > requires a direct child; it does not match deeper descendants. Use a descendant relationship (a space) if any depth inside the container is intended.

Compatibility and advanced syntax

The W3C Selectors Level 4 document is a Working Draft dated 22 January 2026, and it notes that some features are “at-risk” in the standards-process sense. Do not assume every Level 4 feature is implemented uniformly. For advanced selector syntax or cross-browser behavior, check the current documentation for the specific browser and framework versions used by the project; a full browser-by-browser support matrix is not established here.

Or skip the browser setup

If your immediate goal is to capture a page rather than interact with its elements in a test, ScreenshotNeo is a website screenshot API and MCP server. A single GET request can return a PNG, JPEG, WebP, or PDF. For example, this cURL command saves a WebP screenshot of Stripe:

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
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. ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses include X-Page-Verdict and X-Billed headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Frequently Asked Questions

Does a CSS selector identify an element by where it appears on the screen?

No. CSS selectors match elements in the DOM tree by conditions and relationships, not by screen coordinates.

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.

When should I use a role locator instead of CSS in Playwright?

Use a role locator when the test is meant to address an element as a user perceives it; use CSS when stable DOM attributes or relationships clearly express the target.

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.