Automating web testing requires efficiently interacting with elements on HTML and XML pages. CSS Selectors play a crucial role in identifying and manipulating these elements, making them essential for automation frameworks like Selenium.
This CSS Selectors Cheat Sheet provides a structured overview of different CSS Selectors, helping testers quickly locate and interact with web elements for seamless automation.
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.
Why Use CSS Selectors for Automation?
CSS Selectors provide a fast and efficient way to identify and interact with web elements, making them a preferred choice for automation testing frameworks like Selenium and Cypress. Unlike XPath, which can be more complex and performance-heavy, CSS Selectors offer cleaner and more readable expressions to locate elements precisely.
Key Advantages:
- Faster Execution: CSS Selectors are generally faster than XPath in most modern browsers.
- Simpler Syntax: They provide a concise way to locate elements without deeply nested expressions.
- Supports Dynamic Elements: CSS Selectors can handle dynamic elements effectively, especially when combined with pseudo-classes.
Must Read: Xpath Vs CSS Selector: Key Differences
Types of CSS Selectors
CSS Selectors help identify and target elements within a webpage. They can be categorized into four main types based on their functionality:
- Basic Selectors: These are fundamental selectors that target elements using tag names, classes, IDs, or attributes.
- Grouping Selectors: Allow multiple elements to be selected at once, reducing redundancy in code.
- Combinators: Define relationships between elements in the DOM, helping select elements based on hierarchy.
- Pseudo Selectors: Enable selection based on an element’s state or structure, including dynamic interactions and specific parts of elements.
Each type is crucial in styling and automation, allowing for precise and efficient element selection.
Basic CSS Selectors Cheat Sheet
Here is a tabular cheat sheet of the Basic CSS Selectors:
Selector | Description | Code Example |
---|---|---|
Type | This Selector is used when selecting an element based on its HTML Tag. Example: input, div, span | $$(“select”) |
Class | This 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”) |
ID | This 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”) |
Attribute | This 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’]”) |
Also Read: Locators in Selenium: A Detailed Guide
Advanced CSS Selectors Cheat Sheet
Here is the tabular cheat sheet of Advanced CSS Selectors like Grouping Selectors, Combinators, and Pseudo:
1. Grouping Selectors
Selector | Description | Code Example |
---|---|---|
Group | This 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
Selector | Description | Code Example |
---|---|---|
Descendant | As 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”) |
Child | This 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 Sibling | This 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 Sibling | This 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
Pseudo-Classes (:class): Target elements based on state, position, or user interaction.
Selector | Description | Code Example |
---|---|---|
:hover | Selects an element when it is hovered over. | $(“button:hover”) |
:focus | Selects an element when it gains focus (e.g., input fields). | $(“input:focus”) |
:nth-child(n) | Selects elements based on their order within a parent. | $(“li:nth-child(2)”) |
:first-child | Selects the first child of a parent element. | $(“div:first-child”) |
:last-child | Selects the last child of a parent element. | $(“p:last-child”) |
:not(selector) | Selects all elements that do not match a given selector. | $(“div:not(.active)”) |
Pseudo-Elements (::element): Allow styling or inserting content before/after an element.
Selector | Description | Code Example |
---|---|---|
::before | Inserts content before an element’s actual content. | $(“p::before”) |
::after | Inserts content after an element’s actual content. | $(“p::after”) |
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
- Access BrowserStack demo application
- Open dev tools by clicking F12 on keyboard
- Navigate to the Console tab
- Paste the selector given in the Example Column
Also Read: Quick XPath Locators Cheat Sheet
Example: Using CSS Advanced Selectors for Test Automation in Selenium Java
In the below example,
- Accessing the BrowserStack demo application
- Waiting for the Select drop-down to be visible using CSS selectors
- Selecting the value from the drop-down using CSS selector which belongs to Combinators >> Descendant category
Prerequisites:
- Add TestNG dependency to the project
- Add Selenium dependency to the project
- 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(); } }
Useful Resources for CSS
Tutorials
- Advanced CSS Tutorial
- Understanding Sibling Selectors in CSS
- Understanding CSS radial-gradient() function
- How to position Text Over an Image using CSS
- How to resize an image using CSS
- How to use CSS rgba() function correctly?
- Handling Images in HTML and CSS: Everything you need to know
- Dynamic Rendering using HTML and CSS
- Why CSS Position Sticky is Not Working
- A complete guide to CSS Media Query
- CSS Subgrid: What is it and Why do you need it
- What are CSS Breakpoints and Media Query Breakpoints
- How to Create Responsive Designs with CSS
- CSS Selectors in Cypress
- CSS Selector in Selenium: Locate Elements with Examples
- CSS Selectors Cheat Sheet (Basic & Advanced)
Differences
- CSS Grid vs Bootstrap: Which one is better for you?
- What is Responsive CSS vs Reactive CSS?
- Xpath Vs CSS Selector: Key Differences
Frameworks
- Top Responsive CSS Frameworks
- Top 7 CSS Frameworks for Developers
- What are CSS Modules and why use them?
Browser Compatibility & Cross-Browser Testing
- Browser compatibility with CSS Gradients
- Browser Compatibility of Cursor Grab & Grabbing in CSS
- How to Create Browser Compatible Smooth Scrolling with CSS and JavaScript
- How to Create Browser Specific CSS Code
- Fixing Browser Compatibility Issues with CSS Opacity & RGBA
- CSS techniques for Improved Cross Browser Compatibility
Conclusion
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.