Contents

    Guides

    CSS Selectors in Selenium: A Complete 2026 Guide

    Published on

    September 11, 2025
    CSS Selectors in Selenium: A Complete 2026 Guide

    To ensure your website features work correctly, your tests have to be designed to retrieve web pages in real time and execute test workflows. 

    If you are writing a test in Selenium, you can avail CSS selectors that identify IDs of HTML components, classify them, and validate them in a live production environment.

    With CSS selectors, testers can handle both basic and complex test scenarios, such as setting child elements, siblings, or elements with specific attribute values. It enables testers to validate whether the app is behaving properly in the frontend or not. Let’s check more on CSS selectors in Selenium.

    Run Selenium Tests on Cloud

    What is a CSS Selector in Selenium?

    CSS is a locator strategy that helps Selenium locate HTML elements of a web page via the DOM tree. 

    You can identify elements using IDs, classes, tags, attributes, and position relative to other elements. 

    For example, a CSS selector can target a specific button, menu, input field, or link and return its value for Selenium to validate it. Selenium clicks it, enters text, and checks the functionality. 

    CSS selectors also let you combine multiple HTML attributes or element relationships so that you can run automated tests easily and support visual regression. 

    A clear and specific selector makes Selenium tests easier to maintain, especially when working with pages that contain multiple similar elements.

    ‍

    Core CSS Selector Patterns in Selenium

    In Selenium automation, CSS selectors help testers locate the elements they need to interact with during a test. A selector might identify a login field before entering credentials, a button before clicking it, or a message before verifying its content.

    The patterns below cover common ways to locate elements, from simple identifiers such as IDs and classes to relationships between elements in the DOM.

    1. By ID

    The ID of an element is unique within a web page, making it the most precise selector. Using IDs ensures the selection is fast and reliable.

    Syntax: #elementID

    Example: #username

    This selects the element <input id="username">. In Selenium:

    driver.findElement(By.cssSelector("#username")).sendKeys("testuser");

    2. By Class

    Classes can be shared across multiple elements, so using class selectors is useful when you want to target a group of elements or a specific one with a unique combination.‍

    Syntax: .className

    Example: .login-button

    This selects all elements with class="login-button". In Selenium:

    driver.findElement(By.cssSelector(".login-button")).click();

    3. By Tag

    Tag selectors are useful when elements have no unique ID or class but are identified by their HTML tag. This is often combined with other selectors for precision.‍

    Syntax: tagname

    Example: input

    This selects all <input> elements on the page. In Selenium:

    driver.findElements(By.cssSelector("input"));

    4. By Attribute

    Attribute selectors allow targeting elements based on any attribute, not just ID or class. This is useful for forms, buttons, and links.

    Syntax: [attribute='value']

    Example: [type='submit']

    This selects <input type="submit">. In Selenium:

    driver.findElement(By.cssSelector("[type='submit']")).click();

    5. By Multiple Attributes

    Sometimes a single attribute is not enough to uniquely identify an element. Combining attributes increases specificity.‍

    Syntax: [attr1='value1'][attr2='value2']

    Example: [type='text'][name='email']

    This selects <input type="text" name="email">. In Selenium:

    driver.findElement(By.cssSelector("[type='text'][name='email']")).sendKeys("user@example.com");

    6. By Combining Selectors

    Testers can combine tags, classes, IDs, or attributes to narrow down the selection when one identifier matches multiple elements.

    Syntax: tag.class Name or [attr1='value'][attr2='value']

    Example: input[type='text'][name='email']

    This selects:

    <input type="text" name="email>

    In Selenium:

    driver. findElement(By.cssSelector("input[type='text'][name='email']")). sendKeys("user@example.com");

    Extended CSS Selector Strategies

    Advanced CSS selectors help handle elements that are difficult to locate using simple patterns. Using these strategies in Selenium improves test reliability, especially for dynamic or complex web pages.

    1. Substring Matching

    This approach targets elements based on partial attribute values, useful when IDs or classes change dynamically. For example, [id^='user'] selects any element whose ID starts with "user", such as <input id="user123">. 

    Similarly, [class*='btn'] matches elements containing "btn" in their class name, like <button class="submit-btn">. Substring matching ensures tests continue to work even if small changes occur in attribute values.

    2. Parent–Child and Descendant Relationships

    Selecting elements based on hierarchy allows precise targeting. The child selector (>) selects elements directly under a parent, e.g., div > input finds input fields immediately inside a <div>. 

    Descendant selectors (space) capture elements at any depth, e.g., form input selects all input fields within a form. These relationships help handle nested structures without relying on fragile attributes.

    3. Sibling Selectors

    When elements appear sequentially, sibling selectors locate elements relative to others. The adjacent sibling selector (+) targets the next element, e.g., label + input finds an input immediately after a label. The general sibling selector (~) selects all following siblings, useful for grouped form controls or list items.

    4. Grouping Selectors

    Grouping combines multiple selectors to reduce repetition and improve readability. For example, input, select, and textarea selects all standard form fields in a single expression. Grouping simplifies scripts and makes them easier to maintain when multiple elements need the same action.

    5. Pseudo-classes

    Pseudo-classes allow selection based on position or state. Examples include :first-child, :last-child, and :nth-of-type(n). For instance, ul li:nth-of-type(2) selects the second list item in every unordered list. Pseudo-classes are valuable when elements lack unique IDs or consistent attributes, letting testers rely on structure instead.

    CSS Selector Examples in Selenium Test Scripts

    Using CSS selectors in Selenium test scripts helps locate elements quickly and perform actions efficiently. Here are practical examples demonstrating common scenarios:

    1. Selecting Elements by ID‍

    When an element has a unique ID, it is the most reliable selector. For example, to enter a username in a login form:

    driver.findElement(By.cssSelector("#username")).sendKeys("testuser");

    This selects <input id="username"> directly and ensures the action targets the correct field.

    2. Selecting Elements by Class‍

    Classes are useful when multiple elements share the same styling or behavior. For instance, clicking a submit button with class login-button:

    driver.findElement(By.cssSelector(".login-button")).click();

    If multiple buttons exist, combining the class with another attribute improves specificity.

    3. Selecting Elements by Attribute‍

    Attribute selectors handle elements without IDs or unique classes. For example, selecting a submit input field by its type attribute:

    driver.findElement(By.cssSelector("input[type='submit']")).click();

    This works reliably even if the element has dynamic classes.

    4. Combining Multiple Attributes‍

    Combining attributes increases precision when a single attribute is insufficient. For example:

    driver.findElement(By.cssSelector("input[type='text'][name='email']")).sendKeys("user@example.com");

    This ensures only the input field intended for the email is selected, reducing the risk of interacting with the wrong element.

    5. Using Advanced Selectors‍

    Advanced selectors like child, descendant, and pseudo-classes handle complex page structures. For example, selecting the second item in a list inside a form:

    driver.findElement(By.cssSelector("form ul li:nth-of-type(2)")).click();

    This approach is particularly useful for dynamic lists or repeated elements without unique identifiers.

    Best Practices for CSS Selectors in Selenium

    Following best practices ensures that CSS selectors remain reliable, maintainable, and efficient in Selenium test scripts.

    • Prefer IDs when available: If an element has a unique, stable ID, use it directly (#element-id). IDs are the fastest and most reliable way to locate an element and should be the first choice over class or tag-based selectors.‍
    • Avoid overly long selector chains: Selectors like div.container > div.row > div.col > span.label are fragile and break the moment the DOM structure shifts slightly. Keep chains as short as possible while still being specific enough to avoid ambiguity.‍
    • Use attribute selectors for elements without IDs or classes: Attributes like data-testid, name, or aria-label are often more stable than auto-generated class names, especially in frameworks that inject dynamic classes.
    • ‍Favor stable, semantic classes over dynamic ones: Classes tied to visual styling (especially those generated by CSS-in-JS tools) tend to change often. Where possible, target classes that reflect the element's purpose rather than its appearance.‍
    • Use partial matching for dynamic values: Attribute selectors support partial matches (^= for starts-with, $= for ends-with, *= for contains), which helps when a class or attribute includes a variable suffix or prefix.
    • ‍Combine selectors to increase specificity only when needed: Chaining classes or attributes (.btn.btn-primary[data-action='submit']) can help disambiguate elements, but adding unnecessary specificity makes selectors harder to read and more brittle.‍
    • Avoid relying on index-based pseudo-classes unless order is guaranteed: Selectors like :nth-child(3) break easily if the order of elements changes. Use them only when the structure is fixed and predictable.‍
    • Test selectors directly in browser dev tools: Before adding a selector to automation code, validate it using document.querySelectorAll() in the browser console to confirm it matches exactly the intended element(s).‍
    • Keep selectors decoupled from styling changes: Where possible, coordinate with developers to add dedicated test attributes (like data-testid) rather than relying on selectors tied to visual styling, which is more likely to change over time.

    ‍

    CSS Selectors vs. XPath: When to Use Each

    CSS selectors and XPath are both locator strategies used in Selenium to identify elements on a web page. The better choice depends on the element you need to locate and the structure of the DOM.

    CSS selectors are often a straightforward option when an element has stable IDs, classes, or attributes. XPath can be useful when locating an element based on its text, navigating through more complex DOM relationships, or when the required element does not have suitable attributes.

    Criteria CSS Selectors XPath
    Best for Locating elements using IDs, classes, tags, and attributes Locating elements based on complex DOM relationships and conditions
    Readability Often concise for attribute-based selections Can become longer for complex expressions
    Element text Cannot directly locate an element based on its text content Can locate elements based on text
    DOM traversal Supports descendant, child, and sibling relationships Supports more flexible traversal through the DOM
    Attribute matching Supports exact and partial attribute matching Supports attribute-based conditions
    Common use case Stable elements with clear HTML attributes Complex element relationships or text-based identification

    ‍

    When to Use CSS Selectors

    Use CSS selectors when:

    • The element has a stable ID, class, or attribute.
    • You can identify the element without relying on its text content.
    • A concise attribute-based selector is sufficient.
    • The DOM relationship required for the selection is straightforward.

    When to Use XPath

    Use XPath when:

    • You need to locate an element using its visible text.
    • The required element is easier to identify through a complex relationship with another element.
    • You need more flexible traversal through the DOM.
    • CSS selectors cannot express the required selection clearly.

    The goal is not to use CSS selectors or XPath exclusively. Testers should choose the locator strategy that identifies the intended element clearly and remains stable when the application's UI changes.

    ‍

    Conclusion

    By utilizing CSS locators, you can check in real-time how web elements appear and whether they perform in the same way you expected.

    CSS selectors help Selenium locate elements using IDs, classes, attributes, and DOM relationships before interacting with them and validating expected behavior. Stable selectors also reduce locator-related test failures and maintenance.

    When tests uncover unexpected behavior, an effective bug tracking process helps teams document and resolve defects. Teams can also scale Selenium tests across browsers and devices using a real device cloud like BrowserStack.

    ‍

    Data-rich bug reports loved by everyone

    Get visual proof, steps to reproduce and technical logs with one click

    Make bug reporting 50% faster and 100% less painful

    Rating LogosStars
    4.6
    |
    Category leader

    Liked the article? Spread the word

    Put your knowledge to practice

    Try Bird on your next bug - you’ll love it

    “Game changer”

    Julie, Head of QA

    star-ratingstar-ratingstar-ratingstar-ratingstar-rating

    Overall rating: 4.7/5

    Try Bird later, from your desktop