How Pro-Testers Use CSS Selectors In Selenium Automation Scripts?
Tags: css, javascript, programming
Published: 2022-08-16 15:08:00

CSS Selectors in Selenium are used to identifying a user desired HTML web element. This fits into an element locator strategy of automated test development where the primary aim is to interact with page elements through different types of locators. While there are several other methods to identify element locator such as id, name, class name, link text, partial link text, XPath, tag name etc. other than CSS selectors in Selenium we prefer the CSS way due to below benefits.

New to CSS Selectors? Check out this [Ultimate CSS Selector cheat sheet](https://www.lambdatest.com/blog/css-selectors-cheat-sheet/?utm_source=devto&utm_medium=organic&utm_campaign=aug16_kj&utm_term=kj&utm_content=blog) to boost your web designing career.

If you’re new to Selenium and wondering what it is then we recommend checking out our guide — [What is Selenium?](https://www.lambdatest.com/selenium?utm_source=devto&utm_medium=organic&utm_campaign=aug16_kj&utm_term=kj&utm_content=blog)

***Also, Try this online [Selenium Automation](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=aug16_kj&utm_term=kj&utm_content=webpage) Grid to run your browser automation testing scripts.***

## Why Choose CSS Selectors in Selenium Over Other Element Identifiers?

 1. Faster Identification and reduced test execution time — Compared to XPath CSS selectors in Selenium would tend to identify the elements better as most used browsers such as Chrome and Firefox are tuned for better performance with CSS selectors in Selenium. Here is the [link](http://elementalselenium.com/tips/34-xpath-vs-css-revisited-2) which provides performance stats for reference.

 2. Availability of better documentation.

 3. Enhanced readability.

## Different Ways Of Identifying CSS Selectors in Selenium

Let’s discuss the different ways of identifying the CSS [Selenium locators](https://www.lambdatest.com/learning-hub/selenium-locators?utm_source=devto&utm_medium=organic&utm_campaign=aug16_kj&utm_term=kj&utm_content=blog) of web elements.

## Class Selector Conundrum

‘.’ represents a class in CSS and is used to identify web elements with a specific class. For example, if our web element of p is consisting of the class below. The following could be correlated to XPath programming of identifying the class with the tag name [@class = ’value’ ] or it could also be correlated with class name element locator in Selenium.

    <p class=" pages-sub-title"> Lambda Test blog post on validating CSS Selectors in Selenium </p>

CSS selector in Selenium for the same could be identified with the class name as
“.page-sub-title”
The CSS syntax in Selenium of class selector would be –
<.> < Class Name> (or)
<.>

![](https://cdn-images-1.medium.com/max/2732/0*8UncOcadBm2TJuaK.png)

This certification is for anyone who wants to stay ahead among professionals who are growing their career in Selenium automation testing.

Here’s a short glimpse of the Selenium 101 certification from LambdaTest:

{% youtube qx9FPFfJm7E %}

***This [Cypress test automation](https://www.lambdatest.com/blog/cypress-test-automation-framework/?utm_source=devto&utm_medium=organic&utm_campaign=aug16_kj&utm_term=kj&utm_content=blog) tutorial will help you learn the benefits of Cypress automation Check out now.***

## ID Selector Conundrum

‘#’ represents id in CSS and is used to identify web elements with a specific id. Please find an example listed below for matching the web element with ID. If you observe it at a high level this can be compared to that of ID name selector using Selenium methods and also locating the element with id in XPath programming such as tag name [@id = ‘id_value’ ].

    <li id="menu-item-143" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-143">
    <a href="[https://www.lambdatest.com/blog/category/lambdatest-updates/](https://www.lambdatest.com/blog/category/lambdatest-updates/)">Product Updates</a>
    </li>

CSS selector in Selenium for the same could be identified with the class name as
#menu-item-143 or div#menu-item-143

The CSS syntax in Selenium of the ID selector would be –
<#> < ID Name> (or)
<#>

![](https://cdn-images-1.medium.com/max/NaN/0*IKSWvXwEfnKygp_W.png)

## Attribute Selector Conundrum

Attributes could be represented in key-value pairs, for example in the below example we have multiple attributes and values such as ‘role = dialog’, ‘data-dismiss = modal’ etc. Xpath programming version of attribute selector could be correlated as tag name [@attribute key = ‘attribute value’ ].

    <div class="modal fade" id="whitepaper-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
       <span class="close" data-dismiss="modal"  style="top: 4px; position: absolute; right: 10px;">
    <span aria-hidden="true">×</span>
     </span>

CSS selector in Selenium for the same could be identified with the class name as
div[role=’dialog’] or [role=’dialog’]

## ‘Class or ID’ & Attribute Selector Conundrum

Class or ID and attribute combination could serve as a better strategy which is more powerful than that of using a class, id or attribute selector alone. In order to achieve uniqueness of the element, if above 3 ways of identifying fails due to multiple instances of the same locator this could be a go-to solution. Let’s deduct the element locator strategy for below example from our LambdaTest blog.

    <nav id="site navigation" class="navigation main-navigation" role="navigation">

In the above HTML snippet if you observe there is a space in the class name which is “navigation main-navigation” this could be represented as navigation.main-navigation space can be ignored and replaced with ‘.’

CSS Selector in Selenium for the same could be identified as below:

    nav.navigation.main-navigation[role='navigation']

The CSS syntax in Selenium of class or id and attribute selector would be:

    <HTML Tag> <Class Or ID> [ <attribute key> = ‘<attribute value>’ ]

or

    <Class Or ID>  [ <attribute key> = ‘<attribute value>’ ]

## SubString Match Conundrum

In order to enable even powerful querying technique, we can make use of sub-string matches with ^ indicated prefix, $ indicating suffix and * indicating substring. If you observe closely this is similar to the representation of XPath functions such as starts-with, contains and ends with. Let’s get into detailed usage of all the three ways of dealing with matches.

### ^ Indicating a prefix match

Syntax:

    <HTML Tag> [ <Class Or ID> ^= <Class or ID Name> ]

Example:

    div[class^=’aria-label’]

### $ Indicating a suffix match

Syntax:

    <HTML Tag> [ <Class Or ID> $= <Class or ID Name> ]

Example:

    a[class$=’aria-label’]

### * Indicating a substring match

Syntax:

    <HTML Tag> [ <Class Or ID> *= <Class or ID Name> ]

Example

    p[class*=’aria-label’]

## Inner Text Conundrum:

One of the most easily readable syntaxes yet powerful. You can make use of this mechanism to identify text anywhere on the DOM using a string pattern.

Syntax:

    <HTML Tag> <:> <contains> < (text) >

Example

    div:contains("^lambdatest$")

## “Navigating Through Child Elements” — Child Conundrum:

This is an advanced way of handling the element locators through CSS selectors in Selenium while navigating through child elements. There are three possibilities as below:

 1. Direct Child

 2. Sub Child

 3. Nth Child

### Direct Child

Direct child to the parent locator is represented with a ‘>’ symbol. Let’s assume we have a button tag inside a div tag which happens to be a direct child as shown in HTML snippet below.

Example:
<div class="lambdatest-xs-ng">
<button id="tertiary" class="sidebar-container" role="complementary">
div is parent locator and the button is the child locator is represented as:
div.lambdatest-xs-ng>button
Syntax:
Parentlocator > directchildlocator

### Sub Child or Child

Sub child identification includes the same way to identify the elements as that of the direct child but we can ignore ‘>’ symbol as sub child as shown in the example below.

Example:

    <div id="primary" class="content area">
    <div id="content" class="site content" role="main">
    <header class="archive header">
    <h1 class="archive title">Category Archives : Infographics </h1>

Sub Child or child would be represented as:

    div#primary header

Syntax:

    <parent locator=""> <child locator=""> or <sub child="" locator=""></sub></child></parent>

## Nth Child For Opting A Specific Value From A List

This is an advanced way of handling the element locators through CSS selectors in Selenium while navigating through child elements. There are three possibilities as below:

 1. Direct Child

 2. Sub Child

 3. Nth Child

### Direct Child

Direct child to the parent locator is represented with a ‘>’ symbol. Let’s assume we have a button tag inside a div tag which happens to be a direct child as shown in HTML snippet below.

Example:

    <div class="lambdatest-xs-ng">
     <button id="tertiary" class="sidebar-container" role="complementary">

div is parent locator and the button is the child locator is represented as:

    div.lambdatest-xs-ng>button

Syntax:

    Parentlocator &gt; directchildlocator

### Sub Child or Child

Sub child identification includes the same way to identify the elements as that of the direct child but we can ignore ‘>’ symbol as sub child as shown in the example below.

Example:

    <div id="primary" class="content area">
     <div id="content" class="site content" role="main">
     <header class="archive header">
    <h1 class="archive title">Category Archives : Infographics </h1>

Sub Child or child would be represented as:

    div#primary header

Syntax:

    <Parent locator> <child locator> or <sub child locator>

### Nth Child For Opting A Specific Value From A List

N-th child concept would be useful while navigating through ordered or unordered list elements. N becomes the number of the desired list user wants to select. Let’s go through below example to understand how n-th child works. In o

Example:

    <<ul id = "lambdaTestBrowsers">
    <li>Chrome</li>
    <li>Firefox</li>
    <li>Edge</li>
    <li>Safari</li>
    </ul>

Nth child of firefox from the list of lambda test browsers would be represented as:

    #lambdaTestBrowsers li:nth-child(2)

Syntax:

    <HTML Tag> <Clas or ID> <list> <:> <nth-child (number of desired item in the list)>




***Are you using [Playwright automated testing](https://www.lambdatest.com/blog/cypress-test-automation-framework/?utm_source=devto&utm_medium=organic&utm_campaign=aug16_kj&utm_term=kj&utm_content=blog)? Run your Playwright test scripts instantly on 50+ browser/OS combinations using the LambdaTest cloud. Sign up for free.***

## Conclusion

We have come across different identification strategies through the above element locator conundrums. To get familiar with CSS Selectors in Selenium by querying you make use of Chrome dev tools and also there is an open-sourced tool for the same to try out and view results more interactively at [http://flukeout.github.io/](http://flukeout.github.io/). We also discussed the benefits of using CSS selectors in Selenium over other element locators. One of the major drawbacks of the CSS selectors in Selenium is traversing the DOM is not possible with CSS as that of XPath. We can navigate from child to parent and parent to child using XPath. But we can only navigate from parent to child by CSS Selectors in Selenium. If you have any queries or suggestions regarding the CSS Selectors please drop a comment below and I would love to interact. Have fun locating elements through CSS Selectors. Happy testing!