Get Nth Child Selenium

Profile picture for user arilio666
Submitted by arilio666 on

In Selenium you can select the nth child of an element using CSS and XPath Techniques. Let's discuss both in this article.

Table of Contents

  1. Demo Website
  2. Selenium CSS Selector Nth Child
  3. Selenium XPath Nth Child
  4. Video Tutorial

Demo Website

Demo Website

We will click on the dresses tab using nth child.

nth child selenium

Selenium CSS Selector nth-child

Step 1: Select Parent 

Now here above selector covers the entire body of the three tabs under which they are present. So in this case it is the parent.

Step 2: Select all child

Under this ul tag, there are 3 li tags which are the respective tags of Women, Dresses, and T-shirts.

nth-child css selector selenium>li 

Above selector will return all 3 elements.

Step 3: Select nth child using index.>li:nth-child(2)

Selenium XPath nth Child

Step 1: Select Parent


Step 2: Select all Child


Step 3: Select 2nd Child using index 2


or you can also use last minus index



public class AppTest 
    WebDriver driver;
    public void befClass()
        System.setProperty("",System.getProperty("user.dir") + "//drivers//chromedriver");
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    public void LoginTest()
        WebElement childCSS = driver.findElement(By.cssSelector(">li:nth-child(2)"));
        WebElement childXPath = driver.findElement(By.cssSelector("(//ul[contains(@class,'menu-content')]/li)[2]"));