<linearGradient id="sl-pl-bubble-svg-grad01" linear-gradient(90deg, #ff8c59, #ffb37f 24%, #a3bf5f 49%, #7ca63a 75%, #527f32)
Loading ...

QA essentials

Your go-to quality assurance source

CSS Selectors For Test Automation: The Ultimate Guide

Most of QA engineers I know use just a handful of CSS selectors without knowing what they are capable of. I spent a lot of time trying to figure out how to reach certain element. I spent even more time trying to figure out how not to select a certain element. Whether you’re working with Selenium, Cypress, or Playwright, mastering CSS selectors can save you time and frustration. Plus, they make your scripts cleaner, faster, and easier to maintain. Let’s first cover some basics about CSS Selectors for test automation and later in the article I will share the entire cheat sheet.

Short explanation on CSS Selectors

To keep things simple, CSS selectors are patterns used to select and style (or locate) elements on a webpage. Primarily, they are used in web development to style elements on the page, but they are also used in test automation for identifying elements to interact with.

When you’re writing a test script, the most important step is finding the element you want to test – a button, a form field, a dropdown, you name it. That’s where CSS selectors shine. They’re lightweight, versatile, and supported by most modern browsers and frameworks.

It is kind of funny to call them CSS Selectors, when we look for them in HTML document. But the truth is, HTML is used to order the elements on the page and then we link CSS selectors to those elements to give them specific color, text decoration, margins, etc.

Types of CSS Selectors for Automation

1. Basic Selectors

  • Type Selector: Matches elements by their tag name.
    Example: driver.findElements(By.cssSelector("button")) finds all button elements
  • Class Selector (.): Matches elements by class name.
    Example: driver.findElements(By.cssSelector("btn-primary")) selects all elements with the class btn-primary
  • ID Selector (#): Matches a single element by ID.
    Example: driver.findElements(By.cssSelector("btn-primary")) selects the element with some ID submit
css selectors for test automation

2. Attribute Selectors

  • [attr]: Selects elements with a specific attribute.
    Example: driver.findElements(By.cssSelector("[type]")) selects all elements with the type attribute
  • [attr=value]: Matches elements where the attribute equals a specific value.
    Example: driver.findElements(By.cssSelector("[type='text']")) selects input fields of type text
  • [attr^=value]: Matches elements where the attribute starts with a specific value.
    Example: driver.findElements(By.cssSelector("[class^='btn']")) selects elements with class names starting with btn
  • [attr$=value]: Matches elements where the attribute ends with a specific value.
    Example: driver.findElements(By.cssSelector("[href$='.pdf']")) selects links ending with .pdf
  • [attr=value]:* Matches elements where the attribute contains a specific value.
    Example: driver.findElements(By.cssSelector("[data-test*='submit']")) selects elements with data-test containing submit.
    These can be chained also.
    Example: driver.findElements(By.cssSelector("button[data-test*='submit'][class='button']"))
    This would select all elements with tag button, data-test attribute containing submit and class button.

3. Combinators

  • Descendant (): Selects all elements that are descendants of a specified parent.
    Example: driver.findElements(By.cssSelector("div p")) selects all <p> elements inside a <div>
  • Child (>): Selects direct children of a specified element.
    Example: driver.findElements(By.cssSelector("ul > li")) selects <li> elements that are direct children of <ul>
  • And(,): Selects all the matching elements of both noted selectors
    Example: driver.findElements(By.cssSelector("[data-test*='submit'], [class='button']")) selects all elements of data-test attribute containing submit and class button.

4. Pseudo-classes

  • :nth-child(n): Matches elements based on their position in a parent.
    Example: driver.findElements(By.cssSelector("li:nth-child(2)")) selects the second <li> in a list. Note that the nth-child works with 0 based index
  • :first-child / :last-child: Matches the first or last child of a parent.
    Example: driver.findElements(By.cssSelector("div:last-child")) selects the first child <div>
  • :not(): Excludes elements that match a selector.
    Example: driver.findElements(By.cssSelector("input:not([type='text']")) selects all inputs except input fields with type='text' attribute

Best Practices for Using CSS Selectors in Automation

Some of this has been covered already in the article about best locator automation strategy, but here is a shorter version of it.

Prefer IDs and Unique Attributes: When available, use unique identifiers like IDs or custom attributes. There are some reports that these are the fastest. Certainly they are the most reliable selectors.

Avoid Overly Complex Selectors: A selector like div > ul > li > a.btn-primary might work now, but it’s brittle and prone to breaking with layout changes.

Leverage Data Attributes: Many developers add data-* attributes specifically for automation. Use them to make your selectors robust.

Test Your Selectors: Tools like browser DevTools or Selector Playground in Cypress can help you validate selectors quickly.

CSS Selectors Cheat Sheet

Selector TypeSyntax ExampleDescription
Type SelectorbuttonMatches all <button> elements
Class Selector.btn-primaryMatches elements with btn-primary class
ID Selectorsubmit
Matches the element with ID submit
Attribute Selector[type="text"]
Matches inputs of type text
Starts With (^=)[class^="btn"]
Matches classes starting with btn
Ends With ($=)[href$=".pdf"]Matches links ending in .pdf
Contains (*=)[data-test*="submit"]
Matches elements containing submit in the attribute
Descendantdiv pMatches <p> inside a <div>
Childul > liMatches direct children <li> of <ul>
Pseudo-classli:nth-child(2)Matches the second <li> in a list

Wrapping It Up

CSS selectors are the most important part of writing efficient, maintainable test scripts. With the knowledge from this guide, you’re ready to tackle any web automation challenge. Bookmark this page and refer back to the cheat sheet whenever you need help with CSS selectors for test automation. If there are any CSS selectors I haven’t mentioned but you have used it, share your experience in the comment section.

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam! We keep your data private and share it only with third parties that make this service possible. Read our privacy policy for more info.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.