How to obtain the tagname of the parent element in Selenium webdriver?

We can obtain the tagname of the parent element in Selenium webdriver. First of all, we need to identify the child element with help of any of the locators like id, class, name, xpath, or CSS. Then we have to identify the parent with the findElement(By.xpath()) method.

We can identify the parent from the child, by localizing it with the child and then passing (parent::*) as a parameter to the findElement(By.xpath()). Next, to get the tagname of the parent, we have to use the getTagName() method.



Let us identify tagname of the parent of child element li in the below html code −

The tagname of the parent should be ul.


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class ParentTagname{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      // identify element
      WebElement p=driver.findElement(By.xpath("//li[@class='heading']")

      //identify parent from child element
      WebElement t= p.findElement(By.xpath("parent::*"));

      //getTagName() to get parent element tag
      System.out.println("Parent tagname: " + t.getTagName());


Updated on: 22-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started