App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide CSS Selectors Cheat Sheet (Basic & Advanced)

CSS Selectors Cheat Sheet (Basic & Advanced)

By Gurudatt S A, Community Contributor -

Browser Automation requires navigation through the elements of HTML / XML pages to automate its functions for website test automation. Frameworks like Selenium use CSS Selectors to identify web elements and perform the required functions for testing. This comprehensive CSS Advanced Selectors Cheat Sheet discusses various types of CSS Selectors and how to use them in a quick-to-read format.

What is CSS Selector?

Selectors/Locators involve identifying an HTML element to perform actions using Automation tools like Selenium and Cypress. CSS selectors come into the picture when selecting an element based on style sheet information.

A wide variety of CSS selectors are available, allowing for fine-grained precision when selecting elements.

Types of CSS Selectors

CSS Selectors can be broadly grouped into the below categories:

  • Basic Selectors
  • Grouping Selectors
  • Combinators
  • Pseudo

Basic CSS Selectors Cheat Sheet

Here is a tabular cheat sheet of the Basic CSS Selectors:

SelectorDescriptionCode Example
TypeThis Selector is used when selecting an element based on its HTML Tag.

Example: input, div, span

$$(“select”)
ClassThis selector is used when selecting elements based on their Class name.

We need to use the dot “.” followed by the class name for writing this expression

$$(“.sort”)
IDThis selector is used when we need to select elements based on its ID 

We need to use the hash “#” followed by id value for writing this expression

$$(“#offers”)
AttributeThis selector is used when we need to select elements based on its attributes

We need to be using the attribute’s key value inside square brackets “[attr=value]

$$(“[value=’lowestprice’]”)

Advanced CSS Selectors Cheat Sheet

Here is the tabular cheat sheet of Advanced CSS Selectors like Grouping Selectors, Combinators, and Pseudo:

1. Grouping Selectors

SelectorDescriptionCode Example
GroupThis selector uses coma “,” to group all the elements we need to select

This selector is helpful when we need to group elements and select them in one operation

$$(“[id=’offers’], select, option”)

2. Combinators

SelectorDescriptionCode Example
DescendantAs the name suggests, this selector is used when selecting descendants of the parent element.

You need to use space “ ” followed by the descendant element that needs to be selected

$$(“.sort select”)
ChildThis selector is used when we need to select direct child elements for the given parent element

You need to use “>” symbol followed by the child element

$$(“.sort > select”)
General SiblingThis selector is used when we need to select all the siblings concerning the current element

You need to use “~” symbol followed by the sibling element

$$(“#offers ~ a”)
Adjacent SiblingThis selector is used when we need to select the Immediate sibling concerning the current element

You need to use “+” symbol followed by the sibling element

$$(“#offers + a”)

3. Pseudo

SelectorDescriptionCode Example
Pseudo classesThis selector is used when we need to identify/select an element based on its state

We need to use “:” symbol followed by the state; we need to check

$$(“select:enabled”)

Try it out on BrowserStack!

Once you’ve glanced through both the CSS Selectors cheat sheet, you can try out the above different types of CSS Selectors using the below examples 

  1. Access BrowserStack demo application
  2. Open dev tools by clicking F12 on keyboard
  3. Navigate to the Console tab
  4. Paste the selector given in the Example Column

Example: Using CSS Advanced Selectors for Test Automation in Selenium Java

In the below example,

  1. Accessing the BrowserStack demo application 
  2. Waiting for the Select drop-down to be visible using CSS selectors
  3. Selecting the value from the drop-down using CSS selector which belongs to Combinators >> Descendant category

Prerequisites:

  1. Add TestNG dependency to the project
  2. Add Selenium dependency to the project
  3. Download ChromeDriver and update the path in setProperty method.

Code for using Advanced Selectors for Selecting a Drop Down Value using Selenium Java

package com.testng.selenium.v1;

import java.io.File;
import java.time.Duration;
import java.util.NoSuchElementException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class SeleniumTestngTest {
WebDriver driver;

@BeforeTest
public void initDriver() {
String path = System.getProperty("user.dir") + File.separator + "driver" + File.separator
+ "chromedriver";
System.setProperty("webdriver.chrome.driver", path);
driver=new ChromeDriver();
driver.manage().window().maximize();
}

@Test
public void firstTest () {
driver.get("https://www.bstackdemo.com/");
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(40))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".sort select")));
Select select = new Select(driver.findElement(By.cssSelector(".sort select")));
select.selectByVisibleText("Lowest to highest");
}

@AfterTest
public void tearDown() {
driver.close();
driver.quit();
}

}

On a closing note

This article for CSS selectors cheat sheet covers different types of CSS selectors that can be used to build reliable and less flaky locators for automation tools like Selenium and Cypress. Compared to finding elements with XPath, the CSS selector targets specific elements in the DOM with its styling and attribute information.

CSS selector allows us to identify elements based on their properties like their color, background, and state of the element like disabled or enabled. This provides granular control over how we identify and select details.

Using CSS Selectors with Selenium, you can automate various elements on the HTML pages for testing web applications.

Tags
Automated UI Testing Automation Testing Website Testing

Featured Articles

CSS Selector in Selenium: Locate Elements with Examples

What are CSS Breakpoints and Media Query Breakpoints

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.