This blog post is for the CSS Selector fans. Those who choose CSS Selectors over XPATH for identifying elements in there selenium tests.

I have tried my best to capture all the frequently used cases below. In case if I missed something, please let me know in the comments section.

What is CSS and CSS Selector?

CSS stands for Cascading Style Sheets and it describes how HTML elements are to be displayed on screen, paper, or in other media. (Refer: W3 Schools)

In CSS, selectors are patterns used to select the element(s) you want to style.
(Refer: W3 Schools)

Finding elements using CSS Selector

1. Find the element if class attribute value is known

HTML DOM example

<div class="dRYYxd">

CSS Selector command to find the element

$$("div.dRYYxd")

2. Find the element if idattribute value is known

HTML DOM example

<div id="dRYYxd">

CSS Selector command to find the element

$$("div#dRYYxd")

3. Find element if any of the Attribute Value is known (attribute other than id or class)

HTML DOM example

<a ng-click="vm.showHelpSupport()" href="">Support</a>

CSS Selector command to find the element

$$("a[ng-click='vm.showHelpSupport()']")

4. Find the child element if parent element is known

HTML DOM example

<div class="SDkEP">
 <div class="home__redirect"></div>
 <div class="fa fa-chevron-right"></div>
 <div class="fa fa-chevron-left"></div> 
</div>

Find the first child element

$$("div.SDkEP :first-child")

Find the last child element

$$("div.SDkEP :last-child")

Find the nth child element

$$("div.SDkEP :nth-child(2)")

5. Find the sibling element of a known element

HTML DOM example

<div class="SDkEP">
 <div class="a4bIc"></div>
 <div class="fa fa-chevron-right"></div>
 <div class="fa fa-chevron-left"></div> 
</div>

CSS Selector command to find the element

  $$("div.a4bIc+div")

6. Find the element if a part of any of its attribute value is known

When start of the attribute value is known

HTML DOM example

<input aria-label = “testingapplication” id="something" >

CSS Selector command to find the element

$$(“input[aria-label^=’testing’]”)

When end part of the attribute value is known

HTML DOM example

<input aria-label = “testingapplication” id="something" >

CSS Selector command to find the element

$$(“input[aria-label$=’application’]”)

When some part of the attribute value is known

HTML DOM example

<input aria-label = “testingapplication” id="something" >

CSS Selector command to find the element

$$(“input[aria-label*=’ngappl’]”)