Skip to main content

The CSS selectors provide various ways to find child elements from parent elements. Below are few techniques to find the child element.

package com.pb.seltest.util;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class AppTest 
{
    WebDriver driver;
	
    @BeforeClass
    public void befClass()
    {
        System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "//drivers//chromedriver");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        driver.get("http://www.automationpractice.com");
    }
	
    @Test
    public void LoginTest()
    {
        WebElement firstChild = driver.findElement(By.cssSelector("ul[class='sf-menu clearfix menu-content sf-js-enabled sf-arrows']>li:first-child"));
        firstChild.click();
        WebElement lastChild = driver.findElement(By.cssSelector("ul[class='sf-menu clearfix menu-content sf-js-enabled sf-arrows']>li:last-child"));
        lastChild.click();
        WebElement nthChild = driver.findElement(By.cssSelector("ul[class='sf-menu clearfix menu-content sf-js-enabled sf-arrows']>li:nth-child(2)"));
        nthChild.click();	
	}
}

Above code will executed on website automationpractice.com. Here

First child: This will find the first element in the menu, which is Women and click on it.
Last child: This will find the last element under the menu, that is, T-Shirts and click on it.
Nth Child: This will find the  nth element which is second menu item on site with link text Dresses and click on it.

Video Tutorial

About

Elix is a premium wordpress theme for portfolio, freelancer, design agencies and a wide range of other design institutions.