Skip to main content

CSS Selector

A CSS selector is a pattern used to identify one or more HTML elements on a page, based on tag name, class, ID, attributes, or their position in the document — the same syntax used to style pages with CSS, repurposed by test automation tools to locate elements to interact with.

CSS selectors are generally preferred over XPath for locating elements in modern web test automation because they're faster to evaluate, easier to read, and map directly onto the same selectors front-end developers already use — `#submit-button`, `.card:nth-child(2)`, `[data-testid="checkout"]` are all valid CSS selectors a test can target.

The most robust selectors target purpose-built test attributes (like `data-testid`) rather than classes or IDs used for styling, since those are more likely to change for reasons unrelated to the element's identity or purpose — a common source of brittle, frequently-breaking automated tests.

Example

button[data-testid="checkout-submit"]
.cart-item:nth-child(1) .remove-btn
input#email

CSS selectors targeting a test attribute, a nested element, and an ID.

CSS Selector — Definition, Example & How It's Used | QA Bash Glossary | QA Bash