Locating child nodes of WebElements in selenium.


We can locate child nodes of web elements with Selenium webdriver. First of all we need to identify the parent element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the children with the findElements(By.xpath()) method.

We can identify the child nodes from the parent, by localizing it with the parent and then passing ( ./child::*) as a parameter to the findElements(By.xpath())

Syntax−

parent.findElements(By.xpath("./child::*"))

Let us identify the text of the child nodes of ul node in below html code−

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ChildNodes{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement t=driver.findElement(By.xpath("//ul[@class='toc chapters']"));
      //identify child nodes with ./child::* expression in xpath
      List<WebElement> c = t.findElements(By.xpath("./child::*"));
      // iterate child nodes
      for ( WebElement i : c ) {
      //getText() to get text for child nodes
      System.out.println(i.getText());}
      driver.close();
   }
}

Output

Updated on: 18-Sep-2020

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements