9m. WebDriver – Locating elements: Part 3b (by cssSelector contd.)

Hi ninjas! This post is a continuation of our previous post, “9l. WebDriver – Locating elements: Part 3a (by cssSelector)”. Before going any further, please make sure you take a good look at it.

The last two ways of using cssSelector locators which are yet to be discussed are,

  1. Locating child elements
  2. Matching by sub-string

Without further ado, let’s get into action!

1. Locating child elements

It is also possible to locate child elements using cssSelectors.

Let us consider the HTML code,

Anchor tag is the child element of ‘div’. To access the child element,

Using Id:

driver.findElement(By.cssSelector("div#child a"));

# represents ‘id’ and the child element tag is written after a space.

Using class:

driver.findElement(By.cssSelector("div.bg_main a"));

. represents ‘class’

Example: Let us locate the first name text box on the Gmail account sign up page.

Right click on the ‘first name’ text box and select inspect element to get the corresponding HTML code which is as below,

<label id="recovery-email-label">
	<strong>Your current email address</strong>
	<input name="RecoveryEmailAddress" id="RecoveryEmailAddress" value="" 	
               spellcheck="false" type="text">

‘label’ tag’s child element can be accessed with its ‘input’ tag and ‘name’ attribute.


driver.findElement(By.cssSelector("label#recovery-email-label input[name='RecoveryEmailAddress']"));

In case a parent element has multiple child elements (e.g. dropdowns), and they don’t have an ‘id’ or ‘class’ or such attributes to identify, then “nth-of-type” is used to locate a specific child element.

Consider the HTML code,

<ul id="pets">

To identify the child element ‘Dog’,


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

Matching by sub-string

cssSelectors help us to locate elements with sub-strings as well.

Match a prefix (or) begins with

In order to match an element with a known prefix,

Syntax: driver.findElement(By.cssSelector(“tag_name[attribute^=’prefix_value_of_attribute’]”));

Explanation: Locates the element starting with the given prefix. It is represented by ‘^’ symbol.

Considering the below code,

<input value="" name="LastName" id="LastName" spellcheck="false" type="text">

We can see that the ‘input’ tag has an ‘id’ attribute as ‘LastName’. To locate this element, we can specify that find the ‘id’ attribute value that begins with ‘Last’.



Match a suffix (or) ends with

In order to match an element with a known suffix,

Syntax: driver.findElement(By.cssSelector(“tag_name[attribute$=’suffix_value_of_attribute’]”));

Explanation: Locates the element ending with the given suffix. It is represented by ‘$’ symbol.

Considering the below code,

<input name="PasswdAgain" id="PasswdAgain" type="password">

We can see that the ‘input’ tag has a ‘name’ attribute as ‘PasswdAgain’. To locate this element, we can specify that find the ‘name’ attribute value that ends with ‘Again’.



Match a sub-string

In order to match an element with a sub-string,

Syntax: driver.findElement(By.cssSelector(“tag_name[attribute*=’substring_of_attribute_value’]”));

Explanation: Locates the element containing the given sub-string. It is represented by ‘*’ symbol.

Considering the below code,

<input name="PasswdAgain" id="PasswdAgain" type="password">

We can see that the ‘input’ tag has a ‘name’ attribute as ‘PasswdAgain’. To locate this element, we can specify that find the ‘name’ attribute value that contains ‘wdAg’.



Overall picture

Let us see a test case implementing the different ways to use cssSelector locators covered as part of this and the previous post,


  1. Open Firefox browser.
  2. Navigate to google account creation page
  3. Locate ‘First Name’ text box with HTML tag and name attribute
  4. Enter ‘testFirst’ as the first name
  5. Locate ‘Last Name’ text box with a value that begins with a sub-string
  6. Enter ‘testLast’ as last name
  7. Locate ‘Creat a password’ text box with HTML tag , type and name attributes
  8. Enter ‘Pass1234!’ as password
  9. Locate ‘Confirm your password’ text box with a value that contains a sub-string
  10. Enter ‘Pass1234!’ as confirmation password
  11. Locate ‘Mobile phone’ text box with HTML tag and class attribute
  12. Enter ‘9496543210’ as the phone number
  13. Locate ‘Current email address’ text box with child element method
  14. Enter ‘[email protected]
  15. Verify JUnit pane for success result and eclipse IDE console output screen

JUnit code for this scenario is,

package com.blog.junitTests;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ElementLocatorTest3 {
        //Declaring variables
        private WebDriver driver; 
        private String baseUrl;

        public void setUp() throws Exception{
            // Selenium version 3 beta releases require system property set up
            System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
                    + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
            // Create a new instance for the class FirefoxDriver
            // that implements WebDriver interface
            driver = new FirefoxDriver();
            // Implicit wait for 5 seconds
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            // Assign the URL to be invoked to a String variable
            baseUrl = "https://accounts.google.com/SignUp";
        public void testPageTitle() throws Exception{
            // Open baseUrl in Firefox browser window
            // Locate 'First Name' text box by cssSelector: tag and name attribute
            // assign it to a variable of type WebElement
            WebElement firstName = driver.findElement(By.cssSelector("input[name='FirstName']"));
            // Clear the default placeholder or any value present
            // Enter/type the value to the text box
            //Locate 'Last Name' text box by cssSelector: begins with sub-string
            WebElement lastName = driver.findElement(By.cssSelector("input[id^='Last']"));
            //Locate password text box by cssSelector: tag and type, name attributes
            WebElement pwd = driver.findElement(By.cssSelector("input[type='Password'][name='Passwd']"));
            //Locate 'Confirm your password' text box by cssSelector: contains sub-string
            WebElement confirmPwd = driver.findElement(By.cssSelector("input[name*='wdAg']"));
            // Locate Mobile phone text box by cssSelector: tag and class
            WebElement mobileNum = driver.findElement(By.cssSelector("input.i18n_phone_number_input-inner_input")); 
            //Locate "current email address" text box by cssSelector: child element method
            WebElement recoveryEmail = driver.findElement(By.cssSelector("label#recovery-email-label input[name='RecoveryEmailAddress']"));
            recoveryEmail.sendKeys("[email protected]");
          public void tearDown() throws Exception{
            // Close the Firefox browser

Execution result

The comments are clearly provided for each line of code and hence are self-explanatory.

by cssSelector output

In JUnit pane, the green bar shows that the test case is executed successfully. Also, no errors are logged in the console window.

Below image shows the final output executed in Firefox browser.

Browser output

That’s all for today ninjas! See you again in another post.

Have a great day!

Lakshmi Chandana is a Software professional + passion-fueled blogger + novel-reader + artist + tutor to make your day a little brighter than it was before! She is thrilled you are here! She is on a mission to make sure learning sticks but with the fun part kept intact. She uses certain tricks called BrainBells (inspired from barbells and dumbbells used for workout) to achieve this and she says, “this is not the hardest job! As once minions said, it for sure is working in a bubble wrap factory. Imagine the self-control needed!” So, dive in to explore the fun-filled World of Learning!!

One thought

  1. I really like the way concepts are explained! Amazing write-up!! Sample scenarios and code make it all the more easier to understand.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top Search