</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How can we move to the nth child element using XPath?

Use index brackets [n] or position() function in XPath to select nth child elements.

Answer

There are two ways to navigate to the nth child element using XPath:

Method 1: Using Index in Square Brackets
XPATH
//div[2]
//ul/li[3]
//form//input[1]
Method 2: Using position() Function
XPATH
//div[position()=3]
//li[position()>2]
//li[last()]
//li[last()-1]

Table example:

XPATH
//table/tbody/tr[2]
//table/tbody/tr[2]/td[3]
//table/tbody/tr[last()]

Java code:

Java
WebElement thirdItem = driver.findElement(By.xpath("//ul/li[3]"));
System.out.println(thirdItem.getText());

Note: XPath indexing starts from 1, not 0 (unlike Java arrays).

Follow AutomateQA

Related Topics